我有一个单元测试(使用MSTest),如下所示:
[TestMethod]
public void MyTest()
{
var viewModel = new MyViewModel();
viewModel.Run();
//Assert something here
}
Run 是一个返回 void 的异步方法。
假设 Run 的实现方式如下:
public async void Run()
{
//Show a busy indicator here
try
{
var result = await myAsyncModelClass.LongRunningOperation();
//Use the results here
}
finally
{
//Hide the busy indicator here
}
}
myAsyncModelClass.LongRunningOperation()
是一个异步方法,它返回一些 Task<T>
,其中 T 是我的 ViewModel 感兴趣的结果。
我的问题是,我的测试以异步方式运行 Run
方法,因此我的断言在 Run
方法完成之前就被调用了。这很奇怪,因为当我设置断点时,finally 块永远不会被执行,因为断言失败了。如何使 Run
方法同步以便对其进行单元测试?
我也有一个对 myAsyncModelClass.LongRunningOperation()
的单元测试,但我只是调用了 Task<T>.Wait()
,因为它返回一个任务。这使得在单元测试时它变成了同步的。
另外,我想提到的是,Run()
被一个 MVVM 框架神奇地通过 ICommand 调用。 void
可能需要作为返回类型,我将尝试一下。