xUnit.net allows the creation of data-driven tests. These kind of tests get their test data from outside the test method code via parameters added to the test method signature.
Say we had to test a Calculator class and check it’s add method returned the correct results for six different test cases. Without data-driven tests we’d either have to write six separates tests (with almost identical code) or some loop inside our test method containing an assert.
Regular xUnit.net test methods are identified by applying the [Fact] attribute. Data-driven tests instead use the [Theory] attribute.
To get data-driven features and the [Theory] attribute, install the xUnit.net Extensions NuGet package in addition to the standard xUnit.net package.
Creating Inline Data-Driven Tests
The [InlineData] attribute allows us to specify test data that gets passed to the parameters of test method.
So for our Calculator add test we’d start by defining the test method:
[Theory]
public void ShouldAdd(int a, int b, int expectedResult)
{
var sut = new Calculator();
var result = sut.Add(a, b);
Assert.Equal(expectedResult, result);
}
Notice in the test method we have 3 parameters that get used in the test body, including the expected result in the Assert.
Once we’ve defined the test body we can then add the test cases using the [InlineData] attribute, so our six tests cases would look like:
[Theory]
[InlineData(0, 0, 0)]
[InlineData(1, 1, 2)]
[InlineData(2, 2, 4)]
[InlineData(5, 5, 10)]
[InlineData(10, 10, 20)]
[InlineData(1000, 1000, 2000)]
public void ShouldAdd(int a, int b, int expectedResult)
{
var sut = new Calculator();
var result = sut.Add(a, b);
Assert.Equal(expectedResult, result);
}
This test will execute six times, once for each of the [InlineData] attributes. For example, the [InlineData(5, 5, 10)] line will pass 5 to parameter a, 5 to parameter b, and 10 to parameter expectedResult. To add more test cases, we’d just add more [InlineData] attributes.
The xUnit.net extensions also allow the creation of data-driven tests that get their data from other places such as an Excel file or SQL Server.
If you’re new to xUnit.net data-driven tests or to xUnit.net itself, check out my Pluralsight course to learn more: The xUnit.net testing framework.
You can start watching with a Pluralsight free trial.
SHARE: