-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Context_CurrentTest.cs
88 lines (72 loc) · 1.97 KB
/
Context_CurrentTest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
namespace Xunit;
public partial class Context
{
ITest? test;
public ITest Test
{
get
{
InitTest();
return test!;
}
}
MethodInfo? methodInfo;
public MethodInfo MethodInfo
{
get
{
InitTest();
return methodInfo!;
}
}
Type? testType;
public Type TestType
{
get
{
InitTest();
return testType!;
}
}
void InitTest()
{
if (test != null)
{
return;
}
if (TestOutput == null)
{
throw new(MissingTestOutput);
}
#if NET8_0_OR_GREATER
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "test")]
static extern ref ITest GetTest(TestOutputHelper? c);
test = GetTest((TestOutputHelper) TestOutput);
#else
test = (ITest) GetTestMethod(TestOutput)
.GetValue(TestOutput)!;
#endif
var method = (ReflectionMethodInfo) test.TestCase.TestMethod.Method;
var type = (ReflectionTypeInfo) test.TestCase.TestMethod.TestClass.Class;
methodInfo = method.MethodInfo;
testType = type.Type;
}
public const string MissingTestOutput = "ITestOutputHelper has not been set. It is possible that the call to `XunitContext.Register()` is missing, or the current test does not inherit from `XunitContextBase`.";
#if !NET8_0_OR_GREATER
static FieldInfo? cachedTestMember;
static FieldInfo GetTestMethod(ITestOutputHelper testOutput)
{
if (cachedTestMember != null)
{
return cachedTestMember;
}
var testOutputType = testOutput.GetType();
cachedTestMember = testOutputType.GetField("test", BindingFlags.Instance | BindingFlags.NonPublic);
if (cachedTestMember == null)
{
throw new($"Unable to find 'test' field on {testOutputType.FullName}");
}
return cachedTestMember;
}
#endif
}