我在测试异步方法时遇到新手问题。我已经阅读了其他一些帖子,包括如何使用异步方法更正写入测试?,我认为我做的事情是正确的,但我显然错过了一些东西。
这是我要测试的代码:
/// <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;
}
}