NUnit supports parameterized tests through the TestCase attribute. This allows you to specify multiple sets of arguments and will create multiple tests behind the scenes:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestCase(12, 3, 4)] | |
[TestCase(12, 2, 6)] | |
[TestCase(12, 4, 3)] | |
public void DivideTest(int n, int d, int q) | |
{ | |
Assert.AreEqual(q, n / d); | |
} |
However the kind of information that you can pass on through an attribute is rather limited. If you want to pass on complex objects you need a different solution. In that case (no pun intended) you can use the TestCaseSource attribute:
TestCaseSourceAttribute is used on a parameterized test method to identify the source from which the required arguments will be provided. The attribute additionally identifies the method as a test method. The data is kept separate from the test itself and may be used by multiple test methods.
An example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestCaseSource("TestCases")] | |
public async Task GetOrders(Guid correlationId, Customer customer, int expectedCount) | |
{ | |
//Act | |
var orders = await _sut.GetOrders(transportDocument); | |
//Assert | |
Assert.IsNotNull(orders); | |
Assert.AreEqual(expectedCount, orders.Count); | |
} | |
private static readonly object[] TestCases = | |
{ | |
new object[]{ Guid.NewGuid(), new Customer(){Id=1}, 1 }, | |
new object[]{ Guid.NewGuid(), new Customer(){Id=1}, 1 }, | |
new object[]{ Guid.NewGuid(), new Customer(){Id=1}, 1 }, | |
new object[]{ Guid.NewGuid(), new Customer(){Id=1}, 3 } | |
}; |