Skip to content

Unit testing your code

Jon P Smith edited this page Apr 27, 2019 · 4 revisions

Typically you don't use dependency injection in unit testing, so you need a way to get the information you need. I have produced a couple of extension methods to allow you to set up the system and return a UnitTestData instance that contains the IWrappedAutoMapperConfig instance you need to create an instance of the CrudServices or CrudServicesAsync.

NOTE: This would also be useful in serverless applications where you only want to register one or maybe two DTOs.

There are plenty of unit tests to look at, but here is a simple unit test using the UnitTestSetup extension method.

[Fact]
public void TestProjectBookTitleSingleOk()
{
    //SETUP
    var options = SqliteInMemory.CreateOptions<EfCoreContext>();
    using (var context = new EfCoreContext(options))
    {
        context.Database.EnsureCreated();
        context.SeedDatabaseFourBooks();

        var utData = context.SetupSingleDtoAndEntities<BookTitle>();
        var service = new CrudServices(context, utData.ConfigAndMapper);

        //ATTEMPT
        var dto = service.ReadSingle<BookTitle>(1);

        //VERIFY
        service.IsValid.ShouldBeTrue(service.GetAllErrors());
        dto.BookId.ShouldEqual(1);
        dto.Title.ShouldEqual("Refactoring");
    }
}

If you need to register more than one DTO then there is another extension that can do that. e.g.

var utData = context.SetupSingleDtoAndEntities<BookTitle>();
utData.AddSingleDto<BookTitleAndCount>();
//... etc.

You should be aware that I use static ConcurrentDictionarys to cache many things. So, if a test works when you run all the tests, but fails if you run the test on its own, then it is most likely because you have not set up the correct DTO/DbContext in the test that fails on its own.

NOTE: I also would point you to my EfCore.TestSupport library which contains a range of tools for unit testing applications that use EF Core.

Clone this wiki locally