Contents
What should you unit test in your web API controller?
In the arrange step, you will often use mock or stub objects. That minimizes the number of dependencies, so the test is focused on testing one thing. Here are some things that you should unit test in your Web API controllers: The action returns the correct type of response. Invalid parameters return the correct error response.
How is a controller used in unit testing?
The controller is a class like any other class which has members like methods and properties etc. In Unit Testing, we create an instance of the target class and call its method for various inputs and assert the result as per expectation.
How to test controller in ASP.NET Web API 2?
Assume that repository is a mock IProductRepository. It’s important to set Request and Configuration on the controller. Otherwise, the test will fail with an ArgumentNullException or InvalidOperationException. The Post method calls UrlHelper.Link to create links in the response. This requires a little more setup in the unit test:
How to do unit test in RESTful API?
Assert.Equal (HttpStatusCode.OK, (HttpStatusCode)result.StatusCode); Above, either way, the Unit test makes our API robust and validates the implementation of the REST principle following HTTP verbs correctly. Each Controller method should be asserted for all possible types of HTTP Status codes like,
How to redirect a user to another page?
To redirect the user to another page (either external or internal), we can use Redirect method like below. Remember that to redirect to external url, we need to provide complete url starting with http. For internal redirect, url can be provided from root of the application.
What does controller return in web API 2?
In Web API 2, a controller action can return IHttpActionResult, which is analogous to ActionResult in ASP.NET MVC. The IHttpActionResult interface defines a command pattern for creating HTTP responses.