I am trying to write a custom TestMethodAttribute
that allows to annotate a test with some meta information that should be output in the .trx
file generated by the test runner of MSTest.
I therefore implemented the following attribute:
public class CustomTestMethodAttribute : TestMethodAttribute
{
private string _meta1;
private string[] _meta2;
public CustomTestMethodAttribute(string meta1, string[] meta2, string? displayName = null) : base(displayName)
{
_meta1 = meta1;
_meta2 = meta2;
}
public override TestResult[] Execute(ITestMethod testMethod)
{
MethodInfo methodInfo = testMethod.MethodInfo;
Dictionary<string, object> metaProperties = new()
{
{
"task", new Dictionary<string, object>
{
{ "className", testMethod.TestClassName },
{ "method", methodInfo.Name },
{ "meta1", _meta1 },
{ "meta2", _meta2 }
}
}
};
// that is the line that doesn't work
testContext.WriteLine($"META_INFORMATION={JsonSerializer.Serialize(metaProperties)}");
return new TestResult[] { testMethod.Invoke(null) };
}
}
It would allow me to annotate a test method like this:
[CustomTestMethod(meta1: "12345", meta2:new []{"12345", "23456"})]
public void MyTestMethod()
{
...
}
My question is: what’s the easiest way to access the TestContext
in the Execute
method of the CustomTestMethodAttribute
. TestContext
is injected (by MSTest?) into my test class via
[TestClass]
class Test1
{
public TestContext TestContext { get; set; }
...
}
and is therefore accessible within the test method via TestContext
.
If accessing TestContext
is not possible within the attribute – how can I use something like testContext.WriteLine()
in my attribute?
As can be read in the docs:
Used to store information that is provided to unit tests.
This means, that information flow is rather that: test context is provided all information about the test method, which attributes are part of.
And you expect it to be the other way around. Based on this SO post:
TestContext is set automatically by the MSTEST framework but only in the class attributed with [TestClass] and when it executes a test from this class.
So, summing up, what you are after is simply impossible (I also tried with putting TestClass
attribute on TestMethod
attribute, but it did not work… also tried with reflection to no luck).