vendredi 30 octobre 2015

How to clear EF7 InMemory database between tests?

I'm experimenting with the InMemory database provider for EF7. It was easy enough to setup a context and start utilizing it. And it was great when I added my first test which made use of it.

public class NotificationsDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseInMemoryDatabase();
    }

    public DbSet<Notification> Notifications { get; set; }
    public DbSet<NotificationTag> NotificationTags { get; set; }
}

and

public List<Notification> GetUnprocessedNotifications()
{
    var retval = new List<Notification>();

    using (var context = new NotificationsDbContext())
    {
        retval = context.Notifications.Where(n => n.ProcessState == NotificationState.Unprocessed).ToList();
    }
    return retval;
}

and a test

[TestMethod]
public void GetUnprocessedNotifications_Returns_CorrectNotifications()
{
    // setup
    var m = new NotificationManager(_notificationResource, _notificationEngine, _notificationValidation);
    m.CreateNotification(new Notification { Subject = "One", Message = "Test", ProjectId = Guid.NewGuid(), ProcessState = NotificationState.Processed, ProcessedOn = DateTimeOffset.Now });
    m.CreateNotification(new Notification { Subject = "Two", Message = "Test", ProjectId = Guid.NewGuid() });
    m.CreateNotification(new Notification { Subject = "Three", Message = "Test", ProjectId = Guid.NewGuid() });

    var r = m.GetUnprocessedNotifications();

    Assert.AreEqual(2, r.Count);
}

However, when I added my second unit test I started running into issues.

Because the database seems to hang around even when the object the context resides in has been disposed it makes it difficult to predict the results of specific queries when I'm performing my assertions.

Is there a way to wipe the InMemory database besides stopping the application?

Aucun commentaire:

Enregistrer un commentaire