Unit testing

I just started using Entity Framework (v4) and Linq.

I have an Entity data model that was created from a database. Then I implemented the repository classes to implement the business logic for my entities, and they contain my LINQ queries for interacting with entities / database.

What is the easiest and easiest way to unit test methods / functions in my repository classes without getting into the database?

+4
source share
4 answers

You can run your tests against the inmemory database. Check this question

+3
source

Find a framework that allows you to create a mock repository. It will take time at the beginning, but will pay off in the long run.

+1
source

If you can pass IDbSet to your repository that it requests, you can easily write your own implementation of the IDbSet stub that reads and writes to the memory collection mapped to IQueryable , or use a mocking structure to do this for you.

In your production code, you pass an IDbSet from a real DbContext ; in your test code you pass in this stub.

If your test repository references DbContext , you may want to reorganize it so that it only IDbSet to a separate IDbSet .

+1
source

I assume that you simply do not want to load / save any objects in your test (i.e. test only your business logic, not the save level). In this case, you will need a way to easily generate (and reuse) test stubs. The simplest way imo is to create some factories for your various objects that return some simple (but meaningful) entities.

For example, if you tested your User engine, you might want to test a factory that generates different types of users, maybe a user from Wisconsin or a user with a VERY long last name or a user without friends, against a user with 100 friends, etc.

 public static class UserStubFactory { static User NewUserWithLongLastName(int letterCount) { //return user with long last name } static User NewUserWithXFriends(int count) { //return user w/ X friends } } 

Then, when you create other test factories, you can start merging them. Therefore, you might want to test a user with a long last name, and then transfer them to other actions on your system. Well, now you already have TestStub, so you can just call NewUserWithLongLastName () and pass it through your engine.

If you are not from this method, you can also just create them on the fly with constructor syntax.

 User newUser = new User() { LastName ="HOLYCOWTHISISAVERYYLONGLASTNAME"; } 

but I prefer factories for their reuse ratio.

+1
source

All Articles