c# - 单元测试 IHttpActionResult Controller - 200 OK 测试失败

标签 c# unit-testing

这可能是一个相当简单的问题,但我承认,我被困住了。

我有一个返回 IHttpActionResult 的 Controller ,我需要为此编写单元测试。

这是 Controller :

public IHttpActionResult GetPerson(int id) {

    Person person = repository.Get(id);

    if (person == null) {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }

    return Ok(new {
        User = person
    });

}

这是单元测试:

[TestMethod]
public void GetReturnsValidPerson() {

    var userController = new UserController();

    IHttpActionResult actionResult = userController.GetPerson(1);

    Assert.IsInstanceOfType(actionResult, typeof(OkResult));

}

这是测试中的错误:

Assert.IsInstanceOfType failed. Expected type:System.Web.Http.Results.OkResult Actual type: System.Web.Http.Results.OkNegotiatedContentResult1[<>f__AnonymousType11[DataAccess.BO.Person]]

这里到底发生了什么? Controller 返回的是 HTTP 200 Ok 响应。为什么需要 OkNegotiatedContentResult

最佳答案

根据 Asp.Net 文档,IHttpActionResult 的结果是 OkNegotiedContentResult。您的断言比较应该检查这一点。

Unit Testing Controllers in Asp.Net

Action returns 200 (OK) with a response body

The Get method calls Ok(product) if the product is found. In the unit test, make sure the return type is OkNegotiatedContentResult and the returned product has the right ID.

关于c# - 单元测试 IHttpActionResult Controller - 200 OK 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36244611/

相关文章:

c# - 如何使用 SQL CE 4.0 创建内存数据库?

c# - 为什么我的表在 ASP.NET 中没有内容?

java - 使用 PowerMock 模拟私有(private)方法

sql - 在不影响数据库的情况下测试存储过程

android - 在 AndroidTestCase 中访问 AlertDialog

c# - 创建自定义事件日志

c# - NHibernate分层递归查询

c# - PropertyChanged 事件后的 ViewModels 属性始终为 Null

Python:如何模拟 datetime.utcnow()?

c - 退出测试的测试条件