【问题标题】:How write a unit test for asynchronous Web API如何为异步 Web API 编写单元测试
【发布时间】:2016-02-02 18:21:43
【问题描述】:

我有一个 C# 和 Framework 6 项目。我有一个 WEB API 来调用这些方法。 为异步 WebAPI 方法编写单元测试的最佳方法是什么?

这是我的方法:

[HttpGet]
[Route("GetYears")]
public Task<IEnumerable<Year>> GetYearsAsync()
{
     return reditApplicationsRepository.GetYearsAsync();         
}

【问题讨论】:

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


    【解决方案1】:

    您也可以使用await 来执行此操作。

    [TestMethod]
    public async Task GetYearsTest()
    {
        //_sut is the System Under Test,  in this case is an instance of your controller
        var years = await _sut.GetYears();
        //Any Assert that you want
    }
    

    对于存根方法creditApplicationsRepository.GetYearsAsync();的返回使用这个Task.FromResult(mockReturn)

    【讨论】:

    • 你需要使GetYearsTest异步
    • 当然是我的错,因为await.
    【解决方案2】:

    单元测试的主要目标是测试方法内代码的功能。所以异步与否在功能上不应该特别相关。

    所以我会说做这样的事情:

    [TestMethod]
    public void GetYearsTest(){
       //This would assume that your web api class has a mockable repository
       var yourClass = new YourClass(new MockRepository());
    
       //this is going to run your codes synchronously so you can get an immediate result to test on.
       var years = yourClass.GetYears().Result;
    
       //Run whatever test you want to on this
       Assert.IsNotNull(years);
    
    }
    

    如果运行异步测试的目的是确定您的代码是否是线程安全的,那么您将必须发挥创造力来确定如何正确测试您的代码以确保它实际上是安全的。为了帮助我解决这个问题,我需要了解更多关于这里使用的 repo 或者哪些变量可能会导致线程锁定或导致错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      相关资源
      最近更新 更多