DEV Community

Discussion on: Unit Testing With Entity Framework and Entity Framework Core 2.1

Collapse
 
andres profile image
Andrés Pérez • Edited

I have used a different approach, not sure what are your thoughts on it:

public class BaseTest
{
    protected readonly ApplicationDbContext _context;

    public BaseTest()
    {
        var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .Options;

        _context = new ApplicationDbContext(options);

        _context.Database.EnsureCreated();
    }
}

Then in my tests, I inherit from that base class:

public class SomeClassTest : BaseTest, IDisposable
{
    public void Dispose()
    {
        _context.Database.EnsureDeleted();
    }

    [Fact]
    public async Task SomeTest()
    {
        // Here you have access to your _context as usual
        // Arrange
        // Act
        // Assert
    }
}
Collapse
 
pcmichaels profile image
Paul Michaels

I do like this approach, you can also use the test framework 'setup' method (in XUnit it's just the class constructor).

Personally, though, if I was going down this kind of path, I'd probably put the set-up into a static helper method, rather than using inheritance. IMHO it gives better readability to the test.