等待由异步方法所产生的所有线程同时进行单元测试 [英] Waiting for all the threads spawned by async method while unit Testing
问题描述
我的单元测试视图模型在WPF应用程序,有一个代表命令调用方法里面进一步调用异步方法。我要等每一个任务调用断言语句之前完成。通过委托指令调用的方法是像
私人无效Methodcalled()
{
this.uiService.SetBusyState();
UIExecuteHelper executeHelper =新UIExecuteHelper(ViewName.Window);
executeHelper.ExecuteAsync(()=>
{
//一些东西
方法一();
}
}
现在,我在下面的方式在我的单元测试等待方式:
尝试
{
VAR任务= Task.Factory.StartNew(()=>
{
classobj.DelegateCommand.Execute();
});
VAR afterTask = task.ContinueWith((为MyObject)=>
{
classobj.Load();
Assert.AreEqual(真,someflag);
},TaskContinuationOptions.OnlyOnRanToCompletion);}
但它仍然没有等待催生了要完成所有内部任务。请建议
有一个委托命令调用一个方法,其还称里面异步方法。
块引用>@JimWooley正确识别此作为问题的根源。其中一个原因,以避免
异步无效
是因为异步无效
方法不(轻易)测试。最好的办法是什么,他建议:
- 因素命令的实际逻辑放到一个单独的,
工作
-returning方法。- 在委托命令,就像
等待
该方法。- 您的单元测试,然后调用
异步任务
方法,而不是调用委托指令。不过,如果你真的坚持做硬盘的方式,你需要安装一个定制的
的SynchronizationContext
和跟踪异步操作的数量。或者你可以使用我的AsyncContext
类型这会为你这样做:等待AsyncContext.Run(()=> classobj.DelegateCommand.Execute());
classobj.Load();
Assert.AreEqual(真,someflag);I am Unit Testing ViewModel in WPF application and there is a Delegate Command that calls a Method which further calls async method inside it . I have to wait for every Task to be finished before calling Assert statement. the Method called by the delegate command is like :
private void Methodcalled() { this.uiService.SetBusyState(); UIExecuteHelper executeHelper = new UIExecuteHelper(ViewName.Window); executeHelper.ExecuteAsync(() => { // some stuff method1(); } }
Now I am waiting for the method in the following way in my unit test:
try { var task = Task.Factory.StartNew(() => { classobj.DelegateCommand.Execute(); }); var afterTask = task.ContinueWith((myobject)=> { classobj.Load(); Assert.AreEqual(true, someflag); }, TaskContinuationOptions.OnlyOnRanToCompletion); }
But it is still not waiting for all the inner tasks spawned to be finished. Please suggest
解决方案there is a Delegate Command that calls a Method which further calls async method inside it.
@JimWooley correctly identified this as the root of the problem. One of the reasons to avoid
async void
is becauseasync void
methods are not (easily) testable.The best solution is what he suggested:
- Factor the actual logic of the command into a separate,
Task
-returning method.- Within the delegate command, just
await
that method.- Your unit tests can then call the
async Task
method rather than invoking the delegate command.However, if you really insist on doing it the hard way, you'll need to install a custom
SynchronizationContext
and track the number of asynchronous operations. Or you can use myAsyncContext
type which will do this for you:await AsyncContext.Run(() => classobj.DelegateCommand.Execute()); classobj.Load(); Assert.AreEqual(true, someflag);
这篇关于等待由异步方法所产生的所有线程同时进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!