返回 IHttpActionResult 时,如何对 Web api 操作方法进行单元测试? [英] How do I unit test web api action method when it returns IHttpActionResult?

查看:28
本文介绍了返回 IHttpActionResult 时,如何对 Web api 操作方法进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这是我的操作方法

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

测试将

var httpActionResult = controller.Get(1);

在此之后如何检查我的 http 状态代码?

How do I check my http status code after this?

推荐答案

这里 Ok() 只是类型 OkResult 的帮助器,它将响应状态设置为HttpStatusCode.Ok...所以你可以检查你的操作结果的实例是否是一个 OkResult...一些例子(用 XUnit):

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<NotFoundResult>(actionResult);

// if your action returns: Ok()
actionResult = valuesController.Get(11);
Assert.IsType<OkResult>(actionResult);

// if your action was returning data in the body like: Ok<string>("data: 12")
actionResult = valuesController.Get(12);
OkNegotiatedContentResult<string> conNegResult = Assert.IsType<OkNegotiatedContentResult<string>>(actionResult);
Assert.Equal("data: 12", conNegResult.Content);

// if your action was returning data in the body like: Content<string>(HttpStatusCode.Accepted, "some updated data");
actionResult = valuesController.Get(13);
NegotiatedContentResult<string> negResult = Assert.IsType<NegotiatedContentResult<string>>(actionResult);
Assert.Equal(HttpStatusCode.Accepted, negResult.StatusCode);
Assert.Equal("some updated data", negResult.Content);

这篇关于返回 IHttpActionResult 时,如何对 Web api 操作方法进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆