I'm learning about unit tests using Moq, and I have a very simple Webapi Controller that only returns status OK.
public class TestController : ApiController
{
[HttpGet]
[Route("api/v1/test")]
public HttpResponseMessage GetHealth()
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
Well I don't know how to test it using Moq, I will appreciate some help.
No need for Moq I think.
In your unit test you can instantiate a new controller.
var testController = new TestController();
With this you can then call the methods.
[Test]
public void TestHealth(){
var testController = new TestController();
var result = testController.GetHealth() as HttpResponseMessage
Assert.That(result, Is.Not.Null);
Assert.That(result.StatusCode, Is.EqualTo(200));
}
Typically I do not test the Web API level of my controllers and focus on the business logic for mocking and / or integration testing of my code. I don't like to say that you shouldn't test controllers if they contain some logic that needs tested, it's just something that I do not test when building a solution. If my controllers contain logic that need testing I try to abstract what I can into another layer. However, it looks like the Microsoft documentation actually uses the Moq code to test the controller classes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.