Skip to content

Commit 09c2aff

Browse files
authored
Add documentation about the TestContext (#43420)
1 parent eb3cfae commit 09c2aff

File tree

8 files changed

+213
-0
lines changed

8 files changed

+213
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using Microsoft.VisualStudio.TestTools.UnitTesting;
2+
3+
[TestClass]
4+
public class TestClassResultFile
5+
{
6+
public TestContext TestContext { get; set; }
7+
8+
[TestMethod]
9+
public void TestMethodWithResultFile()
10+
{
11+
// Simulate creating a log file for this test
12+
string logFilePath = Path.Combine(TestContext.TestRunDirectory, "TestLog.txt");
13+
File.WriteAllText(logFilePath, "This is a sample log entry for the test.");
14+
15+
// Add the log file to the test result
16+
TestContext.AddResultFile(logFilePath);
17+
18+
// Perform some assertions (example only)
19+
Assert.IsTrue(File.Exists(logFilePath), "The log file was not created.");
20+
Assert.IsTrue(new FileInfo(logFilePath).Length > 0, "The log file is empty.");
21+
}
22+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using Microsoft.VisualStudio.TestTools.UnitTesting;
2+
using System;
3+
4+
namespace YourNamespace
5+
{
6+
[TestClass]
7+
public class CsvDataDrivenTest
8+
{
9+
public TestContext TestContext { get; set; }
10+
11+
[TestMethod]
12+
[DataSource(
13+
"Microsoft.VisualStudio.TestTools.DataSource.CSV",
14+
"|DataDirectory|\\TestData.csv",
15+
"TestData#csv",
16+
DataAccessMethod.Sequential)]
17+
public void TestWithCsvDataSource()
18+
{
19+
// Access data from the current row
20+
int number = Convert.ToInt32(TestContext.DataRow["Number"]);
21+
string name = TestContext.DataRow["Name"].ToString();
22+
23+
Console.WriteLine($"Number: {number}, Name: {name}");
24+
25+
// Example assertions or logic
26+
Assert.IsTrue(number > 0);
27+
Assert.IsFalse(string.IsNullOrEmpty(name));
28+
}
29+
}
30+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using Microsoft.VisualStudio.TestTools.UnitTesting;
2+
3+
[TestClass]
4+
public class MyTestClassTestContext
5+
{
6+
public TestContext TestContext { get; set; }
7+
8+
[AssemblyInitialize]
9+
public static void AssemblyInitialize(TestContext context)
10+
{
11+
// Access TestContext properties and methods here. The properties related to the test run are not available.
12+
}
13+
14+
[ClassInitialize]
15+
public static void ClassInitialize(TestContext context)
16+
{
17+
// Access TestContext properties and methods here. The properties related to the test run are not available.
18+
}
19+
20+
[TestMethod]
21+
public void MyTestMethod()
22+
{
23+
// Access TestContext properties and methods here
24+
}
25+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using Microsoft.VisualStudio.TestTools.UnitTesting;
2+
3+
[TestClass]
4+
public class MyTestClassTestContextThroughCtor
5+
{
6+
private readonly TestContext _testContext;
7+
8+
public MyTestClassTestContextThroughCtor(TestContext testContext)
9+
{
10+
_testContext = testContext;
11+
}
12+
13+
[AssemblyInitialize]
14+
public static void AssemblyInitialize(TestContext context)
15+
{
16+
// Access TestContext properties and methods here. The properties related to the test run are not available.
17+
}
18+
19+
[ClassInitialize]
20+
public static void ClassInitialize(TestContext context)
21+
{
22+
// Access TestContext properties and methods here. The properties related to the test run are not available.
23+
}
24+
25+
[TestMethod]
26+
public void MyTestMethod()
27+
{
28+
// Access TestContext properties and methods here
29+
}
30+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net481</TargetFramework>
5+
<LangVersion>latest</LangVersion>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="MSTest" Version="3.6.3" />
12+
</ItemGroup>
13+
14+
</Project>
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
---
2+
title: MSTest TestContext
3+
description: Learn about the TestContext class of MSTest.
4+
author: Evangelink
5+
ms.author: amauryleve
6+
ms.date: 11/12/2024
7+
---
8+
9+
# The `TestContext` class
10+
11+
The <xref:Microsoft.VisualStudio.TestTools.UnitTesting.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 <xref:Microsoft.VisualStudio.TestTools.UnitTesting> namespace.
12+
13+
## Accessing the `TestContext` object
14+
15+
The <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext> object is available in the following contexts:
16+
17+
- As a parameter to `[AssemblyInitialize]` and `[ClassInitialize]` methods. In this context, the properties related to the test run are not available.
18+
- As a property of a test class. In this context, the properties related to the test run are available.
19+
- As a constructor parameter of a test class (starting with v3.6). This way is recommended over using the property, because it gives access to the object in the constructor. While the property is only available after the constructor has run. This way also helps to ensure immutability of the object and allows the compiler to enforce that the object is not null.
20+
21+
:::code language="csharp" source="snippets/testcontext/csharp/TestContext.cs":::
22+
23+
Or with MSTest 3.6+:
24+
25+
:::code language="csharp" source="snippets/testcontext/csharp/TestContextCtor.cs":::
26+
27+
## The `TestContext` members
28+
29+
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.
30+
31+
### Test run information
32+
33+
The `TestContext` provides information about the test run, such as:
34+
35+
- <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestName> – the name of the currently executing test.
36+
- <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.CurrentTestOutcome> - the result of the current test.
37+
- <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.FullyQualifiedTestClassName> - the full name of the test class.
38+
- <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestRunDirectory> - the directory where the test run is executed.
39+
- <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.DeploymentDirectory> - the directory where the deployment items are located.
40+
- <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.ResultsDirectory> - the directory where the test results are stored. Typically a subdirectory of the `TestRunDirectory`.
41+
- <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestRunResultsDirectory> - the directory where the test results are stored. Typically a subdirectory of the `ResultsDirectory`.
42+
- <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestResultsDirectory> - the directory where the test results are stored. Typically a subdirectory of the `ResultsDirectory`.
43+
44+
In MSTest 3.7 and later, the `TestContext` class also provides new properties helpful for `TestInitialize` and `TestCleanup` methods:
45+
46+
- `TestContext.TestData` - the data that will be provided to the parameterized test method or `null` if the test is not parameterized.
47+
- `TestContext.TestDisplayName` - the display name of the test method.
48+
- `TestContext.TestException` - the exception thrown by either the test method or test initialize, or `null` if the test method did not throw an exception.
49+
50+
### Data-driven tests
51+
52+
In MSTest 3.7 and later, the property `TestData` can be used to access the data for the current test during `TestInitialize` and `TestCleanup` methods.
53+
54+
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](xref:Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceAttribute)-based tests).
55+
56+
Consider the following CSV file `TestData.csv`:
57+
58+
```csv
59+
Number,Name
60+
1,TestValue1
61+
2,TestValue2
62+
3,TestValue3
63+
```
64+
65+
You can use the `DataSource` attribute to read the data from the CSV file:
66+
67+
:::code language="csharp" source="snippets/testcontext/csharp/CsvDataSource.cs":::
68+
69+
### Store and retrieve runtime data
70+
71+
You can use <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.Properties?displayProperty=nameWithType> to store custom key-value pairs that can be accessed across different methods in the same test session.
72+
73+
```csharp
74+
TestContext.Properties["MyKey"] = "MyValue";
75+
string value = TestContext.Properties["MyKey"]?.ToString();
76+
```
77+
78+
### Associate data to a test
79+
80+
The <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.AddResultFile(System.String)?displayProperty=nameWithType> 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.
81+
82+
:::code language="csharp" source="snippets/testcontext/csharp/AddResultFile.cs":::
83+
84+
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.

docs/core/testing/unit-testing-mstest-writing-tests.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,12 @@ MSTest assertions are divided into the following classes:
4747
- [The `StringAssert` class](./unit-testing-mstest-writing-tests-assertions.md#the-stringassert-class)
4848
- [The `CollectionAssert` class](./unit-testing-mstest-writing-tests-assertions.md#the-collectionassert-class)
4949

50+
## The `TestContext` class
51+
52+
The <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext> class provides contextual information and support for test execution, making it easier to retrieve information about the test run and manipulate aspects of the environment. It's defined in the <xref:Microsoft.VisualStudio.TestTools.UnitTesting> namespace and is available when using the MSTest Framework.
53+
54+
For more information, see [Accessing the `TestContext` object](./unit-testing-mstest-writing-tests-testcontext.md#accessing-the-testcontext-object) or [The `TestContext` members](./unit-testing-mstest-writing-tests-testcontext.md#the-testcontext-members).
55+
5056
## Testing private members
5157

5258
You can generate a test for a private method. This generation creates a private accessor class, which instantiates an object of the <xref:Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject> class. The <xref:Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject> class is a wrapper class that uses reflection as part of the private accessor process. The <xref:Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType> class is similar, but is used for calling private static methods instead of calling private instance methods.

docs/navigate/devops-testing/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ items:
8787
href: ../../core/testing/unit-testing-mstest-writing-tests-attributes.md
8888
- name: Assertions
8989
href: ../../core/testing/unit-testing-mstest-writing-tests-assertions.md
90+
- name: TestContext
91+
href: ../../core/testing/unit-testing-mstest-writing-tests-testcontext.md
9092
- name: Running tests
9193
items:
9294
- name: Overview

0 commit comments

Comments
 (0)