Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
TestContext
classThe TestContext class gives useful information and tools to help manage test execution. It lets you access details about the test run and adjust the test environment. This class is part of the Microsoft.VisualStudio.TestTools.UnitTesting namespace.
The TestContext object is available in the following contexts:
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class MyTestClassTestContext
{
public TestContext TestContext { get; set; }
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
// Access TestContext properties and methods here. The properties related to the test run are not available.
}
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
// Access TestContext properties and methods here. The properties related to the test run are not available.
}
[TestMethod]
public void MyTestMethod()
{
// Access TestContext properties and methods here
}
}
Or with MSTest 3.6+:
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class MyTestClassTestContextThroughCtor
{
private readonly TestContext _testContext;
public MyTestClassTestContextThroughCtor(TestContext testContext)
{
_testContext = testContext;
}
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
// Access TestContext properties and methods here. The properties related to the test run are not available.
}
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
// Access TestContext properties and methods here. The properties related to the test run are not available.
}
[TestMethod]
public void MyTestMethod()
{
// Access TestContext properties and methods here
}
}
The TestContext class provides properties about the test run along with methods to manipulate the test environment. This section covers the most commonly used properties and methods.
The TestContext provides information about the test run, such as:
In MSTest 3.7 and later, the TestContext class also provides new properties helpful for TestInitialize
and TestCleanup
methods:
null
if the test is not parameterized.null
if the test method did not throw an exception.In MSTest 3.7 and later, the property TestContext.TestData can be used to access the data for the current test during TestInitialize
and TestCleanup
methods.
When targeting .NET framework, the TestContext enables you to retrieve and set data for each iteration in a data-driven test, using properties like DataRow
and DataConnection
(for DataSource-based tests).
Consider the following CSV file TestData.csv
:
Number,Name
1,TestValue1
2,TestValue2
3,TestValue3
You can use the DataSource
attribute to read the data from the CSV file:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace YourNamespace
{
[TestClass]
public class CsvDataDrivenTest
{
public TestContext TestContext { get; set; }
[TestMethod]
[DataSource(
"Microsoft.VisualStudio.TestTools.DataSource.CSV",
"|DataDirectory|\\TestData.csv",
"TestData#csv",
DataAccessMethod.Sequential)]
public void TestWithCsvDataSource()
{
// Access data from the current row
int number = Convert.ToInt32(TestContext.DataRow["Number"]);
string name = TestContext.DataRow["Name"].ToString();
Console.WriteLine($"Number: {number}, Name: {name}");
// Example assertions or logic
Assert.IsTrue(number > 0);
Assert.IsFalse(string.IsNullOrEmpty(name));
}
}
}
You can use TestContext.Properties to store custom key-value pairs that can be accessed across different methods in the same test session.
TestContext.Properties["MyKey"] = "MyValue";
string value = TestContext.Properties["MyKey"]?.ToString();
The TestContext.AddResultFile(String) method allows you to add a file to the test results, making it available for review in the test output. This can be useful if you generate files during your test (for example, log files, screenshots, or data files) that you want to attach to the test results.
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class TestClassResultFile
{
public TestContext TestContext { get; set; }
[TestMethod]
public void TestMethodWithResultFile()
{
// Simulate creating a log file for this test
string logFilePath = Path.Combine(TestContext.TestRunDirectory, "TestLog.txt");
File.WriteAllText(logFilePath, "This is a sample log entry for the test.");
// Add the log file to the test result
TestContext.AddResultFile(logFilePath);
// Perform some assertions (example only)
Assert.IsTrue(File.Exists(logFilePath), "The log file was not created.");
Assert.IsTrue(new FileInfo(logFilePath).Length > 0, "The log file is empty.");
}
}
You can also use TestContext.Write or TestContext.WriteLine methods to write custom messages directly to the test output. This is especially useful for debugging purposes, as it provides real-time logging information within your test execution context.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowTraining
Module
C# testing in Visual Studio - Training
Start testing your C# apps by using the testing tools in Visual Studio. Learn to write tests, use Test Explorer, create test suites, and apply the red, green, refactor pattern to write code.