Dave Amour
Dave Amour

Reputation: 165

Unit Testing Entity Framework Repository

I am working with TDD and all is going well. When I get to my actual Repository though I don't know how to test this.

Consider the code below - this is what I know I want to write but how do I tackle this in a test first way without doing integration testing.

public class UserDb : IUserDb
{
    public void Add(User user)
    {
        using (var context = new EfContext())
        {
            context.Users.Add(user);

            context.SaveChanges();
        }
    }
}

The link below by forsvarir is what I want to put as an answer. How I can do that?

http://romiller.com/2012/02/14/testing-with-a-fake-dbcontext/

Upvotes: 0

Views: 616

Answers (2)

THBBFT
THBBFT

Reputation: 1211

What are you hoping to achieve by testing the 3rd party tool? You could mock out the context var fakeContext = A.Fake<IDbContext>(); and then assert that an attempt was made to write to the database. A.CallTo(() => fakeContext.SaveChanges()).MustHaveHappened();

The above example uses FakeItEasy mocking library.

Upvotes: 1

prgmtc
prgmtc

Reputation: 750

The usual answer to these kinds of questions is:

  • Isolate the hard to test dependencies (the EF context)
  • Provide a fake implementation in your tests to verify the correct behaviour of the SUT

This all makes sense when you have interesting logic to test in your system under test. For your specific case, the repository looks like a very thin abstraction between your clean domain and EF-aware logic. Good, keep 'em that way. This also means that it's not really doing much work. I suggest that you don't bother writing isolated unit tests (wrapping EF DbContext seems like extra work that might not pull its weight).

Note that I'm not saying you shouldn't test this code: I often tend to test these thin repositories using a real database, i.e. through integrated tests. For all the code that uses these repositories however, I'd stick to isolated unit testing by providing fake repositories to the system under test. That way I have coverage on my repository code and test that EF is actually talking to my database in the correct way and all other tests that indirectly use these repositories are nice, isolated and lightning-fast.

Upvotes: 1

Related Questions