mardi 10 juillet 2018

Testing a class that depends on DbContext - C#

I am pulling my hair out trying to figure out the best solution here, so I am hoping to get some guidance. I feel this question is super specific, but I will try my best to summarize.

We have a 3 year old C# ASP.NET (4.5) MVC web application that serves up content for a health care company. The application makes use of the Entity Framework 6 as an ORM (model/database first) and also uses Simple Injector for dependency injection. This application has several classes that currently depend on the DbContext class directly (via our entity model - MyEntities) - which means that we are tightly coupled to it. In several places, we have code that "news up" an instance of this class to perform database queries on:

var db = new MyEntities();

//perform queries

What I'm trying to do is create an integration test that allows me to do the following:

  1. Create an in-memory representation of the database
  2. Seed some records in the database
  3. Swap this implementation in when running the test
  4. Perform a test on a class that depends on MyEntities (preferably without making sweeping alterations.)

Setting aside the fact that there are libraries to help with in memory testing (namely Effort) - how can I reliably create a "test" version of my entity model and have that injected into the classes I need to test?

Aucun commentaire:

Enregistrer un commentaire