想知道是否有人这样想:

为了在TestInitialize中进行异步调用,这是不正确的设计,因为TestInitialize必须在任何TestMethod之前进行。

可以以任何方式使异步TestInitialize成为正确的方法吗?

    private int val = 0;

    [TestInitialize]
    public async Task  TestMehod1()
    {
        var result = await LongRunningMethod();
        val = 10;
    }

    [TestMethod]
    public void  TestMehod2()
    {
        Assert.AreEqual(10, val);
    }

任何想法?

最佳答案

可能最干净的方法是让TestInitialize启动异步操作,如下所示:

[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);
    }
}

关于c# - MSTEST-异步Testinitialize保证测试失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20375130/

10-12 04:11