ASP. NET MVC uses the MVC architecture, which in itself makes the application easier to test, but that doesn't mean that you can write easy-to-test programs. We all know that unit testing plays a very important role in system development.
Let's write a program that gets the information of a bad man's lover and sends it to his wife.
1. Build a lover ASP. NET MVC3 Project
We need 1 entity classes to store information about men, lovers and wives.
Then we need a loverrepository to get someone's lover, and here we want to retrieve data from the database. We'll go back to the fixed data here.
Build a HomeController, the code is as follows
Create an index view
Create a Send view
F5 Run
2. Refactor this applet.
We can see that if we want to test this action in HomeController, we will not be able to test if loverrepository has not been developed or has gone wrong .
You can see the unit test error.
So how do we isolate loverepository? We all know that interface-oriented programming can improve the testability of the system.
Open LoveRepository.cs, right-click to refactor to interface:
For easy testing, we set this interface property to public.
At this point we can then implement a fakerepository inherited iloverrepository this interface, so that the test passed.
But there are a few questions:
The first is that we expose the properties of HomeController's repository.
Second we have a new object inside the class, and if we get lovers from the database this time, we'll have to modify the code in the controller the next time we want to go from the file or the Web service.
Thirdly, we need to write a fake class ourselves.
To solve these problems, the next section will discuss how the IOC is used by the ASP. MVC3 to solve the object dependency problem.
Reprint: http://www.cnblogs.com/cnblogsfans/archive/2011/09/02/2163633.html
ASP. NET MVC3 Combat series (ii): interface-oriented programming, improve system testability.