简体   繁体   中英

How to create an Entity Framework DbContext for unit testing in TDD?

I'm in the process of learning about Test Driven Development (TDD) so I can use it in a project I've started, but I've run into a question on how to set up a specific type of test I'd like to do.

The scenario is that I have a View that allows someone to edit information about a User (such as username, first name, last name, etc). In many scenarios this User they're editing will already exist in the database, so when they hit save the information gets updated in the database by that View's View Model.

What I'd like to test is that the View Model is saving this information to the database. This is done using an Entity Framework DbContext I pass into the View Model during construction, which means that I need to create a DbContext in the unit test to pass into the View Model that can be updated and compared against.

The Assert I'd like to test would be something along the lines of:

Assert.AreEqual(ViewModelFake.EditedUser.Username, DataBaseContextFake.Users.Find(1).Username);

After the DbContext is originally created by the unit test it populates it with a User, and later in the unit test that User information is changed. The command that's being tested in the View Model is responsible for saving this edited information into the database, replacing what the DbContext was originally populated with.

I've been searching for a solution for the better part of these last two days but haven't been able to track down examples of people doing the same thing. Is this something that should even be handled in a unit test? Please note that I'm not using a repository/unit of work layer on top of Entity Framework.

At work, in our project we created an abstraction over entity framework context.

Imagine that we have an interface, let's call it IMyCompanyContext and that it exposes all methods that you use from DbContext, including the SaveChanges (); method. All database-mapped collections are exposed through this interface using the ICollection interface. The Query provider understands our queries (it checks at runtime that behind that interface is a real DbContext). More than this, you can use an inversion of control aproach, maybe even using a DI Container for requesting a new IMyCompanyContext.

If you want to test this, you just have to implement your context with a bogus context that exposes some lists that you can query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM