本文介绍了异步TestInitialize保证测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在设计上在TestInitialize中进行异步调用不正确,因为TestInitialize必须在任何TestMethod之前发生并且具有固定的签名.
It is incorrect by design to have async call within TestInitialize, as TestInitialize has to happen before any TestMethod and have fixed signature.
这是否也可以以任何方式正确地实现异步TestInitialize?
Can this be correct approach in any way to have async TestInitialize as well?
private int val = 0;
[TestInitialize]
public async Task TestMehod1()
{
var result = await LongRunningMethod();
val = 10;
}
[TestMethod]
public void TestMehod2()
{
Assert.AreEqual(10, val);
}
有什么想法吗?
推荐答案
可能最干净的方法是让 TestInitialize
start 异步操作,如下所示:
Probably the cleanest way to do this is to have TestInitialize
start the asynchronous operation, as such:
[TestClass]
public class UnitTestAsync
{
private Task<int> val = null;
[TestInitialize]
public void TestInitializeMethod()
{
val = TestInitializeMethodAsync();
}
private async Task<int> TestInitializeMethodAsync()
{
return await LongRunningMethod();
}
private async Task<int> LongRunningMethod()
{
await Task.Delay(20);
return 10;
}
[TestMethod]
public async Task TestMehod2()
{
Assert.AreEqual(10, await val);
}
}
这篇关于异步TestInitialize保证测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!