单元测试异步WebAPI 2获取请求

时间:2017-03-01 20:52:12

标签: c# unit-testing asp.net-web-api async-await

我正在尝试测试使用异步的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方法,结果变量中会出现正确的结果,但是当它返回测试方法时,getResult就不算什么了。

我哪里出错了,如何修复它以测试结果?

谢谢!

1 个答案:

答案 0 :(得分:2)

由于getResult不属于NegotiatedContentResult<IEmployee>类型,因此广告系列会为contentResult生成空值。相反,您可能希望转换为OkNegotiatedContentResult<IEmployee>

var contentResult = getResult as OkNegotiatedContentResult<IEmployee>;
相关问题