Reputation: 1093
I have a large SPA application utilizing the Asp.net Web API as backend and angularjs for frontend with repository pattern, UOW and using EntityFramework. Api Controllers are testable too. now, I want to write some Unit Tests to test all api controllers. Now the question is should I use a fake repository and DataContext for Unit Testing Or using the actual database for this purpose?
Which of them is better solution? or is there other approaches?
Thanks
Upvotes: 1
Views: 768
Reputation: 4000
If you want to truly test your controllers, you should do it against a real database.
You should'nt have to unit test your controllers since no real business logic should be in them.
Upvotes: 0
Reputation: 233150
By definition, a Unit Test is an automated test that exercises a unit in isolation of its dependencies. Thus, if you want to unit test, you must replace all dependencies with Test Doubles (Stubs, Mocks, Fakes, etc.).
There are other types of tests. Integration Tests, for example, exercise several units integrated with each other. This could include a database.
When should you choose which? As a rule of thumb, I'd recommend testing according to the Test Pyramid.
Upvotes: 3
Reputation: 8725
Well the answer (as usually) is "it depends". It depends on several thing;
It depends on what you are trying to achieve, how long it takes to run all your UTs, money, the way your system was built and so on...
In the rest of my answer I'm going to ignore most of those concerns.
If your controllers have a logic(behaviour) which you want to verify then, you should inject a fake repository(SoC
, SRP
and etc.. which make it a "Unit").
If you want to verify that the whole controller act as expected(component test), then you should use a real repository(there are a some cases where you want to use a fake repository...).
Usually my controllers act as a Gateway
without any BL
, therefore I have only component/integration tests against them.
My bottom line is: There is no such a thing as best solution to your question, it depends on several things....
The first paragraph of this answer might help you(the test pyramid)
Upvotes: 3