2
using System.Collections.Generic;
3
using System.Reflection;
4
using System.Threading;
1
using System.Reflection;
8
5
public class NUnitAsyncTestMethod : NUnitTestMethod
10
private const string TaskWaitMethod = "Wait";
11
private const string TaskResultProperty = "Result";
12
private const string SystemAggregateException = "System.AggregateException";
13
private const string InnerExceptionsProperty = "InnerExceptions";
14
private const BindingFlags TaskResultPropertyBindingFlags = BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public;
16
7
public NUnitAsyncTestMethod(MethodInfo method) : base(method)
20
protected override object RunTestMethod(TestResult testResult)
22
if (method.ReturnType == typeof (void))
24
return RunVoidAsyncMethod(testResult);
27
return RunTaskAsyncMethod(testResult);
30
private object RunVoidAsyncMethod(TestResult testResult)
32
var previousContext = SynchronizationContext.Current;
33
var currentContext = new AsyncSynchronizationContext();
34
SynchronizationContext.SetSynchronizationContext(currentContext);
38
object result = base.RunTestMethod(testResult);
42
currentContext.WaitForPendingOperationsToComplete();
46
throw new NUnitException("Rethrown", e);
53
SynchronizationContext.SetSynchronizationContext(previousContext);
57
private object RunTaskAsyncMethod(TestResult testResult)
61
object task = base.RunTestMethod(testResult);
63
Reflect.InvokeMethod(method.ReturnType.GetMethod(TaskWaitMethod, new Type[0]), task);
64
PropertyInfo resultProperty = Reflect.GetNamedProperty(method.ReturnType, TaskResultProperty, TaskResultPropertyBindingFlags);
66
return resultProperty != null ? resultProperty.GetValue(task, null) : task;
68
catch (NUnitException e)
70
if (e.InnerException != null &&
71
e.InnerException.GetType().FullName.Equals(SystemAggregateException))
73
IList<Exception> inner = (IList<Exception>)e.InnerException.GetType()
74
.GetProperty(InnerExceptionsProperty).GetValue(e.InnerException, null);
76
throw new NUnitException("Rethrown", inner[0]);
11
protected override object RunTestMethod()
13
using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(method))
15
var result = base.RunTestMethod();
19
return region.WaitForPendingOperationsToComplete(result);
21
catch (AsyncInvocationException e)
23
throw new NUnitException("Rethrown", e.InnerException);
b'\\ No newline at end of file'