mstest单元测试中的意外异步等待行为

时间:2013-03-11 14:19:37

标签: testing asynchronous mstest async-await

我在测试异步方法时遇到新手问题。我已经阅读了其他一些帖子,包括How to correct write test with async methods?,我认为我正在做的事情,但我显然遗漏了一些东西。

这是我要测试的代码:

/// <summary>
/// Temporary method used to simulate the time required to generate a report.
/// </summary>
public virtual async Task GenerateTestReportAsync()
{
    ++ActiveTaskCounter;

    await Task.Delay(2000);

    --ActiveTaskCounter;
}

这是测试(是的,我可以/应该通过将ActiveTaskCounter值存储在列表中来改进它,但这不是重点):

[TestMethod]
public async Task GenerateTestReportAsyncUpdatesActiveTaskCounter()

    var bayViewModel = CreateBayViewModel();

    var invocationCount = 0;
    bayViewModel.PropertyChanged += (sender, args) =>
        {
            if (args.PropertyName == "ActiveTaskCounter")
            {
                ++invocationCount;
            }
        };

    await bayViewModel.GenerateTestReportAsync();

    //Thread.Sleep(2100); // TODO: Why is this needed?
    Assert.AreEqual(2, invocationCount);
    Assert.AreEqual(0, bayViewModel.ActiveTaskCounter);
}

测试总是通过Thread.Sleep取消注释。它总是失败,Thread.Sleep发表了评论,如上所示。为什么是这样?我假设“await bayViewModel.GenerateTestReportAsync()”下面的代码甚至不会执行,直到GenerateTestReportAsync 真的完成。

是的,我正在使用: Microsoft Visual Studio Ultimate 2012 版本11.0.51106.01更新1 Microsoft .NET Framework 版本4.5.50709

感谢您提供的任何帮助!这令我难过: - |

编辑:这是视图模型类的最小重现...

using System.ComponentModel;
using System.Threading.Tasks;

public class BayViewModel : INotifyPropertyChanged
{
    public BayViewModel()
    {
        PropertyChanged = (sender, args) => { };
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private int _activeTaskCounter;
    public int ActiveTaskCounter
    {
        get
        {
            return _activeTaskCounter;
        }
        set
        {
            _activeTaskCounter = value;
            PropertyChanged(this, new PropertyChangedEventArgs("ActiveTaskCounter"));
        }
    }

    public virtual async Task GenerateTestReportAsync()
    {
        ++ActiveTaskCounter;

        await Task.Delay(2000);

        --ActiveTaskCounter;
    }
}

0 个答案:

没有答案