Saturday, November 4, 2017

Entity Framework Core - InMemory Db Names in Tests

The new in memory database provider that's available for EF Core is awesome. If you aren't familiar with it, it lives in the "Microsoft.EntityFrameworkCore.InMemory" NuGet package. One of the quirks of using this provider is that it requires a unique database name for each test. This ensures that you don't have state bleed over between tests. The creation of the in memory database usually looks something like this.
 var options = new DbContextOptionsBuilder()
                .UseInMemoryDatabase(databaseName: "Unique_db_name_here")
                .Options;
At first when writing tests I was utilizing a magic string as in the example above. I came back to some unit test where I'd used unique names such as "test1", "test2" etc. After deleting a test and seeing my magic strings get out of sequence, it became apparent that this was going to be a maintainability nightmare. Hmmm, did I use "test6" yet?

Unit tests methods already have unique names, so why not use the test name? With magic strings this approach would be terrible, but with the C# 6.0 nameof operator this approach works well.


This keeps the in memory names unique and keeps refactoring simple.

No comments:

Post a Comment