我有Visual Studio 2012和需要同步上下文的异步测试 但是MSTest的默认同步上下文为空 我想测试在具有同步上下文的WPF或WinForms-UI线程上运行 将SynchronizationContext添加到测试线程的最佳方法是什么?
[TestMethod]
public async Task MyTest()
{
Assert.IsNotNull( SynchronizationContext.Current );
await MyTestAsync();
DoSomethingOnTheSameThread();
}
答案 0 :(得分:6)
您可以创建自定义的SynchronizationContext派生类,并将其注册为SynchronizationContext.SetSynchronizationContext的当前上下文。阅读Stephen Toub关于“Await, SynchronizationContext, and Console Apps”和“Await, SynchronizationContext, and Console Apps: Part 2”的帖子。
您的自定义SynchronizationContext只需覆盖接收异步执行回调的Post方法。你如何执行它们取决于你。
第一篇文章提供了一个同步上下文,它将所有发布的操作存储在一个队列中,一个阻塞循环从队列中获取操作并在一个线程中执行它们。
答案 1 :(得分:6)
您可以在名为SynchronizationContext
的{{3}}中使用单线程AsyncContext
:
[TestMethod]
public void MyTest()
{
AsyncContext.Run(async () =>
{
Assert.IsNotNull( SynchronizationContext.Current );
await MyTestAsync();
DoSomethingOnTheSameThread();
});
}
但是,这并未完全伪造特定的UI环境,例如,Dispatcher.CurrentDispatcher
仍然是null
。如果您需要该级别的伪造,则应使用原始Async CTP中的SynchronizationContext
实现。它附带了三个可用于测试的SynchronizationContext
实现:一个通用的(类似于我的AsyncContext
),一个用于WinForms,一个用于WPF。
答案 2 :(得分:6)
使用Panagiotis Kanavos和Stephen Cleary的信息,我可以像这样编写我的测试方法:
[TestMethod]
public void MyTest()
{
Helper.RunInWpfSyncContext( async () =>
{
Assert.IsNotNull( SynchronizationContext.Current );
await MyTestAsync();
DoSomethingOnTheSameThread();
});
}
内部代码现在在WPF同步上下文中运行,并处理用于MSTest的所有异常。 Helper方法来自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);
}
}
答案 3 :(得分:0)
可以声明您自己的测试方法属性,您可以在其中在测试运行中注入自定义代码。使用它,您可以用自己的[SynchronizationContextTestMethod]替换[TestMethod]属性,该属性自动使用上下文集运行测试(仅在VS2019中进行测试):
public class SynchronizationContextTestMethodAttribute : TestMethodAttribute
{
public override TestResult[] Execute(ITestMethod testMethod)
{
Func<Task> function = async () =>
{
var declaringType = testMethod.MethodInfo.DeclaringType;
var instance = Activator.CreateInstance(declaringType);
await InvokeMethodsWithAttribute<TestInitializeAttribute>(instance, declaringType);
await (Task)testMethod.MethodInfo.Invoke(instance, null);
await InvokeMethodsWithAttribute<TestCleanupAttribute>(instance, declaringType);
};
var result = new TestResult();
result.Outcome = UnitTestOutcome.Passed;
var stopwatch = Stopwatch.StartNew();
try
{
RunInSyncContext(function);
}
catch (Exception ex)
{
result.Outcome = UnitTestOutcome.Failed;
result.TestFailureException = ex;
}
result.Duration = stopwatch.Elapsed;
return new[] { result };
}
private static async Task InvokeMethodsWithAttribute<A>(object instance, Type declaringType) where A : Attribute
{
if (declaringType.BaseType != typeof(object))
await InvokeMethodsWithAttribute<A>(instance, declaringType.BaseType);
var methods = declaringType.GetMethods(BindingFlags.Instance | BindingFlags.Public);
foreach (var methodInfo in methods)
if (methodInfo.DeclaringType == declaringType && methodInfo.GetCustomAttribute<A>() != null)
{
if (methodInfo.ReturnType == typeof(Task))
{
var task = (Task)methodInfo.Invoke(instance, null);
if (task != null)
await task;
}
else
methodInfo.Invoke(instance, null);
}
}
public static void RunInSyncContext(Func<Task> function)
{
if (function == null)
throw new ArgumentNullException(nameof(function));
var prevContext = SynchronizationContext.Current;
try
{
var syncContext = new DispatcherSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(syncContext);
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(prevContext);
}
}
}