问题描述
我的Visual Studio 2012和异步测试,需要一个同步上下文。结果
但MSTest的默认同步上下文为空。结果
我想测试作为具有同步上下文WPF-或WinForms的UI线程运行。结果
什么是最好的方法,以一个SynchronizationContext的添加到测试线程?
[TestMethod的]
公共异步任务MyTest的()
{
Assert.IsNotNull(SynchronizationContext.Current);
等待MyTestAsync();
DoSomethingOnTheSameThread();
}
使用从帕纳约蒂斯Kanavos和斯蒂芬·克利里的信息,我可以写我的testmethods是这样的:
[TestMethod的]
公共无效MyTest的()
{
Helper.RunInWpfSyncContext(异步()=>
{
Assert.IsNotNull(SynchronizationContext.Current);
等待MyTestAsync();
DoSomethingOnTheSameThread();
});
}
内code现在运行在一个WPF同步上下文并处理与用于MSTest的所有异常。
辅助方法是从斯蒂芬Toub:
使用System.Windows.Threading程序; //调度WPF程序集WindowsBase公共静态无效RunInWpfSyncContext(Func键<任务>功能)
{
如果(函数== NULL)抛出新的ArgumentNullException(功能);
VAR prevCtx = SynchronizationContext.Current;
尝试
{
VAR syncCtx =新DispatcherSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(syncCtx); VAR任务=()的函数;
如果(任务== NULL)抛出新的InvalidOperationException异常(); VAR帧=新DispatcherFrame();
VAR T2 = task.ContinueWith(X => {frame.Continue = FALSE;},TaskScheduler.Default);
Dispatcher.PushFrame(架); //执行所有任务,直到frame.Continue ==假 task.GetAwaiter()调用getResult()。 //当任务失败重新抛出异常
}
最后
{
SynchronizationContext.SetSynchronizationContext(prevCtx);
}
}
I have Visual Studio 2012 and an asynchronous test that needs a synchronization context.
But the default synchronization context of MSTest is null.
I would like to test as running on a WPF- or WinForms-UI thread that has a synchronization context.
What's the best method to add a SynchronizationContext to the test thread ?
[TestMethod]
public async Task MyTest()
{
Assert.IsNotNull( SynchronizationContext.Current );
await MyTestAsync();
DoSomethingOnTheSameThread();
}
Using the informations from Panagiotis Kanavos and Stephen Cleary, I can write my testmethods like this:
[TestMethod]
public void MyTest()
{
Helper.RunInWpfSyncContext( async () =>
{
Assert.IsNotNull( SynchronizationContext.Current );
await MyTestAsync();
DoSomethingOnTheSameThread();
});
}
The inner code now runs in a WPF synchronization context and handles all exceptions as used for MSTest.The Helper method is from Stephen Toub:
using System.Windows.Threading; // WPF Dispatcher from assembly 'WindowsBase'
public static void RunInWpfSyncContext( Func<Task> function )
{
if (function == null) throw new ArgumentNullException("function");
var prevCtx = SynchronizationContext.Current;
try
{
var syncCtx = new DispatcherSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(syncCtx);
var task = function();
if (task == null) throw new InvalidOperationException();
var frame = new DispatcherFrame();
var t2 = task.ContinueWith(x=>{frame.Continue = false;}, TaskScheduler.Default);
Dispatcher.PushFrame(frame); // execute all tasks until frame.Continue == false
task.GetAwaiter().GetResult(); // rethrow exception when task has failed
}
finally
{
SynchronizationContext.SetSynchronizationContext(prevCtx);
}
}
这篇关于如何同步上下文添加到异步测试方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!