In ASP. when testing the Controller in net MVC, you often need to access the context in the controller, for example, querying the content in a string or form. However, when testing, it is generally not in the Web runtime environment, so we need to do some work to simulate the context.
ControllerCodeAs follows:
PublicActionresult index ()
{
Viewdata ["Message"]=Request. querystring ["Linear Filter"];
ReturnView ();
}
The test syntax is as follows:
Code
[Testmethod]
Public Void Index ()
{
Homecontroller Controller = New Homecontroller ();
VaR httpcontext = New Mock < Httpcontextbase > ();
VaR request = New Mock < Httprequestbase > ();
Namevaluecollection querystring = New Namevaluecollection ();
Querystring. Add ( " Linear Filter " , " Linear Filter " );
Request. Setup (R => R. querystring). Returns (querystring );
Httpcontext. Setup (HT => Ht. Request). Returns (request. Object );
Controllercontext = New Controllercontext ();
Controllercontext. httpcontext = Httpcontext. object;
Controller. controllercontext = Controllercontext;
Viewresult result = Controller. Index () As Viewresult;
Viewdatadictionary viewdata = Result. viewdata;
Assert. areequal ( " Linear Filter " , Viewdata [ " Message " ]);
}
Mock is used here for reference:
Moq (Mock framework based on. net3.5, C #3.0)
If it is form, just make a slight modification:
PublicActionresult about ()
{
Viewdata ["Message"]=Request. Form ["Linear Filter"];
ReturnView ();
}
Test code:
Code
[Testmethod]
Public Void About ()
{
// Arrange
Homecontroller Controller = New Homecontroller ();
VaR httpcontext = New Mock < Httpcontextbase > ();
VaR request = New Mock < Httprequestbase > ();
Namevaluecollection querystring = New Namevaluecollection ();
Querystring. Add ( " Linear Filter " , " Linear Filter " );
Request. Setup (R => R. Form). Returns (querystring );
Httpcontext. Setup (HT => Ht. Request). Returns (request. Object );
Controllercontext = New Controllercontext ();
Controllercontext. httpcontext = Httpcontext. object;
Controller. controllercontext = Controllercontext;
// Act
Viewresult result = Controller. About () As Viewresult;
// Assert
Viewdatadictionary viewdata = Result. viewdata;
Assert. areequal ( " Linear Filter " , Viewdata [ " Message " ]);
}