In an MVC4 C# website, we are using Unit Testing to test our code. What we are currently doing is creating a mock database, then testing each layer:
- Test the Database – connecting, initializing, load, etc.
- Test the code accessing the database
- Test the view layer
I want these three categories to be run in order and only if the previous one passed. Is this the right way to go about it? The old way we were doing it was using a Dependency Injection framework was a weird approach to mock testing. We actually created a mock class for each data accessor, which sucks because we have to re implement the logic of each method, and it didn’t really add any value because if we made a mistake with the logic the first time, we’ll make it a second.
No. You should be test everything in isolation and because of that any failing data access code should be completely unrelated to the view. So the view unit tests should fail for a completely different reason and because of that you should always run all tests.
In general, tests should run in isolation, and should not depend on any other tests. It seems to me that the view layer still depends on the data access code, but that you only abstracted the layer below. In that case, from the view’s perspective, you are mocking an indirect dependency, which makes your unit tests more complex than strictly needed.
I’m not sure if I get this, but it seems as if you were using the DI container inside your unit tests. This is a absolute no-no. Don’t clutter your tests with any DI framework. And there’s no need to. Just design your classes around the dependency injection principle (expose all dependencies as constructor arguments) and in your test you just manually new up the class under test with fake dependencies -or- when this leads to repetitive code, create a factory method in your test class that creates a new instance of the class under test.
I’m not sure, but it sounds as if there’s something wrong with your design here. You would normally have a
IRepository<T>interface for which you would have multiple implementations, such as aUserRepository : IRepository<User>, andOrderRepository : IRepository<Order>. In your test suite, you will have one genericFakeRespository<T>orInMemoryRepository<T>and you’re done. No need to mock many classes here.Here are two great books you should definitely read:
Those books will change your life. And since you’ll be reading anyway, do read this book as well (not related to your question, but code be a life changer as well).