In the development project process, there will always be a large number of auxiliary methods, such as string processing, code validation, format output and so on. If you find yourself writing similar code multiple times, you might want to think about how to extract the code into a helper method (or even a class library or framework, where the granularity problem is not discussed here). The role of the helper method, in addition to following the dry principle, makes the code easier to write, clearer and more readable-and as long as you "do", you will find it not difficult to get these benefits.
Here is a simple example of a unit test of the index method:
[TestMethod]
public void indextest ()
{
Useridentity identity = new useridentity ();
mock Mockcontroller.setup (c => c.identity). Returns (identity);
var result = MockController.Object.Index () as Viewresult;
if (result = = null)
{
throw new Exception ("The result are expected to being viewresult but not.");
}
Assert.AreEqual (""), result. ViewName,
"The view name is expected to being the default one but ' {0} '", result. ViewName);
Assert.AreEqual (""), result. Mastername,
"The master name is expected to being the default one but ' {0} '", result. Mastername);
var model = result. Viewdata.model as Indexmodel;
if (model = = null)
{
throw new Exception ("model is expected to being indexmodel but not.");
}
Assert.AreEqual (identity, model. Identity);
Assert.AreEqual ("Welcome to asp.net mvc!", model. message);
}
Starting at the end of the line from "var result = ..." is an assertion of the results of the index method invocation, which includes the following points:
The return value is the Viewresult object
ViewName is the default value
Mastername is the default string
Model as Indexmodel Object
Each property of model is the correct value
This essential five-point requirement takes up more than 10 lines of code (though they are all very clear). If each unit test method needs to write this code, this is certainly a tedious thing. At this point, you can provide an auxiliary method to simplify the writing of unit tests.