【发布时间】:2017-03-01 20:52:11
【问题描述】:
我正在尝试测试使用异步的 Web api 方法,但它们从不返回结果。
控制方法如下:
[HttpGet]
[Route("{id}")]
[ResponseType(typeof(IEmployee))]
public async Task<IHttpActionResult> Get(string id)
{
try
{
IEmployee result = await _repoEmployee.GetEmployeeAsync(id);
return Ok(result);
}
catch (Exception ex)
{
logit.Error($@"An error occurred while trying to get Employee for Employee number ""{id}"".", ex);
throw;
}
}
这是使用 NUnit 的测试:
[TestCase("0677")]
public async Task EmployeeController_Get_GiveValidEmpID_Success(string employeeNumber)
{
Setup();
// Act
IHttpActionResult getResult = await _controller.Get(employeeNumber);
var contentResult = getResult as NegotiatedContentResult<IEmployee>;
// Assert
Assert.IsNotNull(contentResult);
Assert.AreEqual(HttpStatusCode.Accepted, contentResult.StatusCode);
Assert.IsNotNull(contentResult.Content);
Assert.AreEqual(employeeNumber, contentResult.Content.Person.EmployeeNumber);
}
如果我调试 Get 方法,正确的结果会出现在 result 变量中,但是当它返回到测试方法时,getResult 什么都没有。
我哪里出错了,我该如何解决它以测试结果?
谢谢!
【问题讨论】:
-
是
getResult为空还是contentResult为空? -
contentResult 为空。我无法从 getResult 的即时窗口中得到任何东西。
-
所以
contentResult为空,因为getResult不是NegotiatedContentResult<IEmployee>类型 -
改用
OkNegotiatedContentResult<IEmployee>。 -
就是这样。谢谢!我想我需要复习一下 web api 2。
标签: c# unit-testing asp.net-web-api async-await