Search code examples
c#unit-testingasp.net-coreentity-framework-coreasp.net-core-mvc-2.0

Unit Testing when using EF Core 2.0


For the project I am doing in my internship we have to use a repository pattern. Since the project was already using EF Core and I read that there was already repository and unit of work in the underlying implementation. I figured I would just use the EF Core methods directly without implementing repository classes as I wanted to prevent clutter.

Well now I am in a bit of a problem, I can't seem to find much useful information on unit testing when I implement this way. The requirement is a hard requirement, and I required 100% coverage of CRUD functions within my controllers due to the standards of this firm. I found some of the Microsoft Documentation here, here, and the integration testing using SQLite but I still can't seem to figure out unit testing. I did some googling as well and I can't find resources aside from integration testing.

Is there some way I can unit test using EF Core directly, or am I gonna have to make repositories in order to properly unit test this program?


Solution

  • Since you do not have a separate repository, you do not have to unit test your repository; you cannot unit test what you don’t have.

    What you would usually test with EF Core would be actual database access. For that, you can use the in-memory database to temporarily set up your database which you can run full tests against. Of course, this is more an integration test than a minimal unit test.

    But you should think about this: When you write unit tests, you have to have an actual idea of what you are testing. Just saying “I need unit tests for component X” does not make real sense. Usually, it would be more like “I need unit tests for methods U, W, Y of component X”. So unless you actually have methods with real behavior that you need to test, attempting to write unit tests for the database context just makes no sense.

    You only want to unit test things things that you write yourself. If there’s nothing, e.g. because you are using the direct database context functionalities for CRUD, then there’s nothing to test. The EF Core project is already covering their side with unit tests, and you probably don’t want to start unit testing third party code here.