You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You can use the Microsoft unit test framework for managed code to set up a unit test method to retrieve values from a data source. The method is run successively for each row in the data source, which makes it easy to test a variety of input by using a single method.
25
+
You can use the Microsoft unit test framework (MSTest) for managed code to set up a unit test method to retrieve values from a data source. The method is run successively for each row in the data source, which makes it easy to test a variety of input by using a single method.
26
26
27
-
Creating a data-driven unit test involves the following steps:
27
+
A data-driven unit test can use any of the following kind:
28
28
29
-
1. Create a data source that contains the values that you use in the test method. The data source can be any type that is registered on the machine that runs the test.
30
-
31
-
2. Add a private <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext> field and a public `TestContext` property to the test class.
32
-
33
-
3. Create a unit test method and add a <xref:Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceAttribute> attribute to it.
34
-
35
-
4. Use the <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.DataRow%2A> indexer property to retrieve the values that you use in a test.
29
+
- inline data using the `DataRow` attribute
30
+
- member data using the `DynamicData` attribute
31
+
- from some well-known source provider using the `DataSource` attribute
36
32
37
33
## The method under test
38
34
@@ -54,15 +50,94 @@ We'll test a method in `Maths` that adds two integers using a loop:
54
50
publicintAddIntegers(intfirst, intsecond)
55
51
{
56
52
intsum=first;
57
-
for( inti=0; i<second; i++)
53
+
for (inti=0; i<second; i++)
58
54
{
59
55
sum+=1;
60
56
}
57
+
61
58
returnsum;
62
59
}
63
60
```
64
61
65
-
## Create a data source
62
+
## Test test method
63
+
64
+
### Inline data-driven test
65
+
66
+
For inline tests, MSTest uses `DataRow` to specify values used by the data-driven test. The test in this example runs successively for each data row.
67
+
68
+
```csharp
69
+
[DataTestMethod]
70
+
[DataRow(1, 1, 2)]
71
+
[DataRow(2, 2, 4)]
72
+
[DataRow(3, 3, 6)]
73
+
[DataRow(0, 0, 1)] // The test run with this row fails
MSTest uses `DynamicData` attribute to specify the name, kind (property, the default, or method) and defining type (by default current type is used) of the member that will provide the data used by the data-driven test.
87
+
88
+
```csharp
89
+
publicstaticIEnumerable<object[]>AdditionData
90
+
{
91
+
get
92
+
{
93
+
returnnew[]
94
+
{
95
+
newobject[] { 1, 1, 2 },
96
+
newobject[] { 2, 2, 4 },
97
+
newobject[] { 3, 3, 6 },
98
+
newobject[] { 0, 0, 1 }, // The test run with this row fails
It is also possible to override the default generated display name, using the `DynamicDataDisplayName` property of the `DynamicData` attribute. The display name method signature must be `publc static string` and accept two parameters, the first of type `MethodInfo` and the second of type `object[]`.
Creating a data source driven unit test involves the following steps:
129
+
130
+
1. Create a data source that contains the values that you use in the test method. The data source can be any type that is registered on the machine that runs the test.
131
+
132
+
2. Add a public `TestContext` property of type <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext> to the test class.
133
+
134
+
3. Create a unit test method
135
+
136
+
4. Add a <xref:Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceAttribute> attribute to it.
137
+
138
+
5. Use the <xref:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.DataRow%2A> indexer property to retrieve the values that you use in a test.
139
+
140
+
#### Create a data source
66
141
67
142
To test the `AddIntegers` method, create a data source that specifies a range of values for the parameters and the sum that you expect to be returned. In this example, we'll create a Sql Compact database named `MathsData` and a table named `AddIntegersData` that contains the following column names and values
68
143
@@ -72,31 +147,26 @@ To test the `AddIntegers` method, create a data source that specifies a range of
72
147
|1|1|2|
73
148
|2|-3|-1|
74
149
75
-
## Add a TestContext to the test class
150
+
####Add a TestContext to the test class
76
151
77
152
The unit test framework creates a `TestContext` object to store the data source information for a data-driven test. The framework then sets this object as the value of the `TestContext` property that you create.
78
153
79
154
```csharp
80
-
privateTestContexttestContextInstance;
81
-
publicTestContextTestContext
82
-
{
83
-
get { returntestContextInstance; }
84
-
set { testContextInstance=value; }
85
-
}
155
+
publicTestContextTestContext { get; set; }
86
156
```
87
157
88
158
In your test method, you access the data through the `DataRow` indexer property of the `TestContext`.
89
159
90
160
> [!NOTE]
91
-
> .NET Core does not support the [DataSource](xref:Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceAttribute) attribute. If you try to access test data in this way in a .NET Coreor UWP unit test project, you'll see an error similar to **"'TestContext' does not contain a definition for 'DataRow' and no accessible extension method 'DataRow' accepting a first argument of type 'TestContext' could be found (are you missing a using directive or an assembly reference?)"**.
161
+
> .NET Core does not support the [DataSource](xref:Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceAttribute) attribute. If you try to access test data in this way in a .NET Core, UWP or WinUI unit test project, you will see an error similar to **"'TestContext' does not contain a definition for 'DataRow' and no accessible extension method 'DataRow' accepting a first argument of type 'TestContext' could be found (are you missing a using directive or an assembly reference?)"**.
92
162
93
-
## Write the test method
163
+
####Write the test method
94
164
95
165
The test method for `AddIntegers` is fairly simple. For each row in the data source, call `AddIntegers` with the **FirstNumber** and **SecondNumber** column values as parameters, and verify the return value against **Sum** column value:
96
166
97
167
```csharp
168
+
[TestMethod]
98
169
[DataSource(@"Provider=Microsoft.SqlServerCe.Client.4.0; Data Source=C:\Data\MathsData.sdf;", "Numbers")]
99
-
[TestMethod()]
100
170
publicvoidAddIntegers_FromDataSourceTest()
101
171
{
102
172
vartarget=newMaths();
@@ -105,16 +175,14 @@ public void AddIntegers_FromDataSourceTest()
The `Assert` method includes a message that displays the `x` and `y` values of a failed iteration. By default, the asserted values - `expected` and `actual` - are already included in failed test details.
116
-
117
-
### Specify the DataSourceAttribute
185
+
#### Specify the DataSourceAttribute
118
186
119
187
The `DataSource` attribute specifies the connection string for the data source and the name of the table that you use in the test method. The exact information in the connection string differs, depending on what kind of data source you are using. In this example, we used a SqlServerCe database.
120
188
@@ -149,7 +217,7 @@ The connection strings depend on the type of the type of data source, but it sho
149
217
)]
150
218
```
151
219
152
-
### Use TestContext.DataRow to access the data
220
+
####Use TestContext.DataRow to access the data
153
221
154
222
To access the data in the `AddIntegersData` table, use the `TestContext.DataRow` indexer. `DataRow` is a <xref:System.Data.DataRow> object, so retrieve column values by index or column names. Because the values are returned as objects, convert them to the appropriate type:
155
223
@@ -166,26 +234,10 @@ The test results bar at the top of **Test Explorer** is animated as your test ru
166
234
> [!NOTE]
167
235
> There's a result for each row of data and also one summary result. If the test passed on each row of data, the summary run shows as **Passed**. If the test failed on any data row, the summary run shows as **Failed**.
168
236
169
-
If you ran the `AddIntegers_FromDataSourceTest` method in our example, the results bar turns red and the test method is moved to the **Failed Tests**. A data-driven test fails if any of the iterated methods from the data source fails. When you choose a failed data-driven test in the **Test Explorer** window, the details pane displays the results of each iteration that is identified by the data row index. In our example, it appears that the `AddIntegers` algorithm does not handle negative values correctly.
237
+
If you ran any of the`AddIntegers_FromDataRowTest`, `AddIntegers_FromDynamicDataTest` or`AddIntegers_FromDataSourceTest` method in our example, the results bar turns red and the test method is moved to the **Failed Tests**. A data-driven test fails if any of the iterated methods from the data source fails. When you choose a failed data-driven test in the **Test Explorer** window, the details pane displays the results of each iteration that is identified by the data row index. In our example, it appears that the `AddIntegers` algorithm does not handle negative values correctly.
170
238
171
239
When the method under test is corrected and the test rerun, the results bar turns green and the test method is moved to the **Passed Test** group.
172
240
173
-
## Run an inline data-driven test
174
-
175
-
For inline tests, MSTest uses `DataRow` to retrieve values from a data source. The test in this example runs successively for each data row.
176
-
177
-
```csharp
178
-
[DataTestMethod]
179
-
[DataRow(1, 1, 2)]
180
-
[DataRow(2, 2, 4)]
181
-
[DataRow(3, 3, 6)]
182
-
[DataRow(0, 0, 1)] // The test run with this row fails
Copy file name to clipboardExpand all lines: docs/test/unit-test-basics.md
+3-27Lines changed: 3 additions & 27 deletions
Original file line number
Diff line number
Diff line change
@@ -1,7 +1,7 @@
1
1
---
2
2
title: Unit testing fundamentals
3
3
description: Learn how Visual Studio Test Explorer provides a flexible and efficient way to run your unit tests and view their results.
4
-
ms.date: 12/28/2021
4
+
ms.date: 10/17/2021
5
5
ms.topic: conceptual
6
6
f1_keywords:
7
7
- vs.UnitTest.CreateUnitTest
@@ -298,33 +298,9 @@ Learn more details about [debugging unit tests](../debugger/debugger-feature-tou
298
298
299
299
**Q: Can I create unit tests that take multiple sets of data as input to run the test?**
300
300
301
-
**A:** Yes. *Data-driven test methods* let you test a range of values with a single unit test method. Use a `DataSource` attribute for the test method that specifies the data source and table that contains the variable values that you want to test. In the method body, you assign the row values to variables using the `TestContext.DataRow[`*ColumnName*`]` indexer.
301
+
**A:** Yes. *Data-driven test methods* let you test a range of values with a single unit test method. Use a `DataRow`, `DynamicData` or `DataSource` attribute for the test method that specifies the data source that contains the variable values that you want to test.
302
302
303
-
> [!NOTE]
304
-
> These procedures apply only to test methods that you write by using the Microsoft unit test framework for managed code. If you're using a different framework, consult the framework documentation for equivalent functionality.
305
-
306
-
For example, assume we add an unnecessary method to the `CheckingAccount` class that is named `AddIntegerHelper`. `AddIntegerHelper` adds two integers.
307
-
308
-
To create a data-driven test for the `AddIntegerHelper` method, we first create an Access database named *AccountsTest.accdb* and a table named `AddIntegerHelperData`. The `AddIntegerHelperData` table defines columns to specify the first and second operands of the addition and a column to specify the expected result. We fill a number of rows with appropriate values.
The attributed method runs once for each row in the table. **Test Explorer** reports a test failure for the method if any of the iterations fail. The test results detail pane for the method shows you the pass/fail status method for each row of data.
303
+
The attributed method runs once for each row in the data source. **Test Explorer** reports a test failure for the method if any of the iterations fail. The test results detail pane for the method shows you the pass/fail status method for each row of data.
328
304
329
305
Learn more about [data-driven unit tests](../test/how-to-create-a-data-driven-unit-test.md).
0 commit comments