For example, we have a controller in the Web API project
public class Somecontroller:apicontroller{public Httpresponsemessage Get () {//Some operations return Request.createresponse ( Httpstatuscode.ok, Somemodel);}}
If you call Somecontroller's Get () method directly in the unit test, you will receive a exception hint that the request is null.
So we need to construct a request in the test code, in two ways
1. Simple Construction method
[testmethod]public void Unittestmethod () {//Environment preparation Part YourNameSpace.Controllers.SomeController Controller = new Somecontroller ();//The following two statements are constructs a simple request message controller. Request = new Httprequestmessage (); controller. Request.setconfiguration (New Httpconfiguration ()); var result = Controller. Get ();//Assertion}
2. More controllable structure
[testmethod]public void Unittestmethod () {//Environment preparation Part YourNameSpace.Controllers.SomeController Controller = new Somecontroller (); var config = new httpconfiguration (); var request = new Httprequestmessage (httpmethod.post, "Yoururl"); var route = config. Routes.maphttproute ("Defaultapi", "Api/{controller}/{id}"), var routedata = new Httproutedata (route, new httproutevaluedictionary {"Controller", "Products"}}), Controller. ControllerContext = new Httpcontrollercontext (config, routedata, request); Controller. Request = Request;controller. Request.properties[httppropertykeys.httpconfigurationkey] = Config;var result = Controller. Get ();//Assertion}
You can then run the unit test to see the results.