Unit Testing – Why Create a Repository Twice in C#?

asp.net-mvccunit testing

The other day I was reading a little about Unit Testing and I saw some examples where people create a repository interface (i.e. IExampleRepository) and then create the real repository (public class ExampleRepository : IExampleRepository) and a repository to be used for unit testing (FakeExampleRepository : IExampleRepository).

In the IExampleRepository they were implementing the same methods as in the ExampleRepository, however with different Linq queries.

What is exactly the objective here? I thought one part of unit testing your code is make sure that a method works correctly? But when I use two totally different queries, one for 'real' and one in the test, how much sense does the test make?

Best Answer

One of the aims of unit testing is to test just one thing at a time i.e. a single class and method. If the repository itself is not under test then you would normally mock this out in some way so as just to test the logic in your method/class.

That said you do also need to test with a 'real' repository*, but this would normally be done in an integration/system test

*obviously real as in repo set up for test, hopefully not e.g. the production DB.