Download example:
Http://files.cnblogs.com/chsword/MyTestMvc.rar
Next, let's explain how to establish a test.
Asp. netMvc provides testing functions.
When creating Asp. netMVCApplication, click OK. A query for Create Project Test is displayed.
If Yes is selected, a "project name + Test" Test project is automatically created.
The test project references the Rhino. Mock (Latest Version 3.4) open source project (http://www.ayende.com/projects/rhino-mocks/downloads.aspx)
There is nothing to say about the test code. After reading the examples, we can naturally understand that Scott's MockHelpers makes the test more convenient.
You can use the following code for testing: [TestMethod]
Public void Index (){
HomeController home = new HomeController ();
Var viewengin = new FakeViewEngine ();
Home. ViewEngine = viewengin;
MockRepository mock = new MockRepository ();
Using (mock. Record ()){
Mock. SetFakeControllerContext (home );
}
Using (mock. Playback ()){
Home. Index ();
Assert. AreEqual ("Index", viewengin. ViewContext. ViewName );
}
}
Example
This example provides a logon function.
There are two pages
The/Post/Index page can be viewed only after logon.
The/Post page can only be viewed by logged-on admin users.
Otherwise, an Error occurs.
I wrote an extension method when verifying logon. Public static class ControllerExtension
{
Public static bool IsPost (this Controller controller ){
Return controller. Request. Form. Count> 0;
}
}
When Logging On, I use Session to save user logon information.
All user information I initialize in Global RegisterRoutes (RouteTable. Routes );
// Replace the Application with the database
Application ["Posts"] = new List <Post> (); // a collection of accounts
Application ["Accounts"] = new List <Account> (); // a set of posts
// Initialize two accounts
List <Account> la = Application ["Accounts"] as List <Account>;
La. Add (new Account () // This is the Administrator
{
Username = "admin ",
Password = "admin"
});
La. Add (new Account () // This is a common user
{
Username = "user ",
Password = "user"
});
You just need to read the code and catch a cold... it's quite uncomfortable... three volumes of toilet paper)
Asp.net Mvc Framework Series