【问题标题】:unit testing an async method tests assertions before method has completed单元测试异步方法在方法完成之前测试断言
【发布时间】:2019-05-28 11:28:55
【问题描述】:
[TestMethod]
public void TestMethod1()
{
    TestClass testClass = new TestClass();
    testClass.Method();
    Assert.AreEqual(testClass.x, true);
}

和测试类:

public async void Method()
{
    if(cond)
        await InnerMethod();
}

private async Task InnerMethod()
{
    var data = await client.FetchData();
    x = data.res;
}

我正在测试这种格式的同步方法。但是当我运行测试时,它会通过这条线 var data = await client.FetchData();

然后不是继续执行方法,而是首先进入测试方法中的断言语句(失败,因为显然它没有完成方法)。然后继续该方法的其余部分。

我真的很困惑为什么要这样做,但我猜测它与线程有关。关于为什么这种行为真的很有帮助的任何线索!谢谢

【问题讨论】:

  • 避免异步无效。被测方法和测试方法本身应该返回一个任务。这样就可以等待被测方法了。
  • 制作你的测试方法public async Task TestMethod1()await testClass.Method();
  • 请注意,您现在可以将测试方法声明为异步,因此您应该拥有[TestMethod] public async Task TestMethod1()

标签: c# .net unit-testing asynchronous vs-unit-testing-framework


【解决方案1】:

使您的测试方法也异步public async Task TestMethod1() 并在测试await testClass.Method(); 中等待。我不确定 MSTest,但它适用于 xUnit。

正如下面评论中所写,您应该使用public async Task Method1()。阅读Async/Await - Best Practices in Asynchronous Programming

【讨论】:

  • 还将public async void Method() 更改为public async Task Method()(异步测试方法确实适用于Visual Studio 2017 及更高版本)
  • 仅供参考,所有现代测试框架都支持这一点,其中“现代”是“很久以前”。就像 2013 年左右一样。
猜你喜欢
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 2011-11-07
  • 2015-09-04
  • 2012-08-28
  • 2017-12-21
  • 1970-01-01
  • 2021-09-19
相关资源
最近更新 更多