How do I unit test web api action method when it returns IHttpActionResult?

后端 未结 6 1665
你的背包
你的背包 2020-12-07 08:03

Let\'s assume this is my action method

public IHttpActionResult Get(int id)
{
    var status = GetSomething(id);
    if (status)
    {
        return Ok();
          


        
6条回答
  •  囚心锁ツ
    2020-12-07 08:51

    Here Ok() is just a helper for the type OkResult which sets the response status to be HttpStatusCode.Ok...so you can just check if the instance of your action result is an OkResult...some examples(written in XUnit):

    // if your action returns: NotFound()
    IHttpActionResult actionResult = valuesController.Get(10);
    Assert.IsType(actionResult);
    
    // if your action returns: Ok()
    actionResult = valuesController.Get(11);
    Assert.IsType(actionResult);
    
    // if your action was returning data in the body like: Ok("data: 12")
    actionResult = valuesController.Get(12);
    OkNegotiatedContentResult conNegResult = Assert.IsType>(actionResult);
    Assert.Equal("data: 12", conNegResult.Content);
    
    // if your action was returning data in the body like: Content(HttpStatusCode.Accepted, "some updated data");
    actionResult = valuesController.Get(13);
    NegotiatedContentResult negResult = Assert.IsType>(actionResult);
    Assert.Equal(HttpStatusCode.Accepted, negResult.StatusCode);
    Assert.Equal("some updated data", negResult.Content);
    

提交回复
热议问题