WEB API Unit Test notation

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.