TestContext is null when invoking method using Reflection
I am invoking a Data Driven Test Method from another service using Reflection. This Data Driven test read the data from file using TestContext and it is null. The purpose of this service is to run all the End to End tests available in the UnitTest1 class.
When I am running the same test using Test Explorer, it works fine.
Below is the code block for the Unit Test Class:
[TestClass]
class UnitTest1
{
public TestContext TestContext {get; set;}
[TestMethod]
[DeploymentItem("Data.xml")]
[DataSource(
"Microsoft.VisualStudio.TestTools.DataSource.XML",
"Data.xml",
"DataParameters",
DataAccessMethod.Sequential)]
[Timeout(60000)]
public void TestMethod1()
{
string field1 = this.TestContext.DataRow["Field1"].ToString();
string field2 = this.TestContext.DataRow["Field2"].ToString();
}
[TestMethod]
[DeploymentItem("Data.xml")]
[Timeout(60000)]
public void VerifyDataFile()
{
string file = "Data.xml";
Assert.IsTrue(File.Exists(file), "deployment failed: " + file + " did not get deployed");
}
}
The csproj of the Unit Test Project:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net472</TargetFramework>
<RuntimeIdentifier>win7-x64</RuntimeIdentifier>
</PropertyGroup>
<-- Some dependencies -->
<ItemGroup>
<Content Include="..\..\..\folder\Data.xml" Link="Data.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
Now the Project class code from where this Unit test is getting called:
public class ExecuteTests
{
private UnitTest1 unitTestObj;
public ExecuteTests()
{
this.unitTestObj = UnitTest1();
}
public void RunAll()
{
MethodInfo[] methods = unitTestObj.GetType().GetMethods();
foreach (MethodInfo? method in methods)
{
var task = method.Invoke(unitTestObj, new object?[0]);
}
}
}
It gives the following error:
Object reference not set to an instance of an object.
while debugging I got to know TestContext is null when test method is getting called using reflection. Is there any way to set the expected TestContext so the reflection code does not fail?
2 answers
Sort by: Most helpful
-
Deleted
This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.
5 deleted comments
Comments have been turned off. Learn more
-
Deleted
This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.
Comments have been turned off. Learn more