这可能是一个相当简单的问题,但我承认,我被困住了。
我有一个返回 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/