【问题标题】:Unit Test Async WebAPI 2 Get Request单元测试异步 WebAPI 2 获取请求
【发布时间】: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&lt;IEmployee&gt; 类型
  • 改用OkNegotiatedContentResult&lt;IEmployee&gt;
  • 就是这样。谢谢!我想我需要复习一下 web api 2。

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


【解决方案1】:

因为getResult 不是NegotiatedContentResult&lt;IEmployee&gt; 类型,所以转换导致contentResult 的值为空。相反,您可能想要转换为 OkNegotiatedContentResult&lt;IEmployee&gt;:

var contentResult = getResult as OkNegotiatedContentResult<IEmployee>;

【讨论】:

    猜你喜欢
    • 2014-02-27
    • 1970-01-01
    • 2014-09-01
    • 2016-03-08
    • 2012-07-15
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多