I am working on an ASP.net MVC 3.0 Application. I am using MSTest
along with Moq
for unit testing. I have written all the test methods for my controllers and ran those tests , which gave successful results.
Now, I have a doubt whether I have properly made unit testing. Because, almost most of my controller actions contains database calls.
I am not mocking them , I am mocking only Session
and Request
objects using Moq.
Is it really necessary to mock database calls, since unit testing means testing a single unit of code? I think unit testing controller with database calls violates above statement.
If it is so, can any one explain me how to mock database calls? I am not using any Entity Framework.
Updated2:
[httppost]
public void AjaxSave(Model m)
{
m.update(); // Database call
}
Best Answer
You should extract code which makes database calls into separate object (take a look on Single Responsibility Principle). E.g. you have controller
Extract data-access code into separate class (usually such classes called repositories):
As you already notices I declared abstraction which is implemented by data-access class:
Make controller depend on this abstraction (it's important - abstraction is easy to mock):
Then inject repository implementation into controller (Dependency Injection in .NET) and mock it for tests: