NUnit [TestCase] attribute provides running a single test with a different set of parameters and you don't have to write separate tests for each parameter. Let us say we have the following class and want to test the IsLatitudeValid()
method:
public class CoordinateValidator
{
public bool IsLatitudeValid(double latitude)
{
return latitude is >= -90 and <= 90;
}
public bool IsLongitudeValid(double longitude)
{
return longitude is >= -180 and <= 180;
}
}
We can use the following test method:
[TestCase(-90, true)]
[TestCase(0, true)]
[TestCase(10, true)]
[TestCase(90, true)]
[TestCase(-91, false)]
[TestCase(91, false)]
public void TestLatitude(double latitude, bool expected)
{
// ARRANGE
var validator = new CoordinateValidator();
// ACT
bool valid = validator.IsLatitudeValid(latitude);
// ASSERT
Assert.AreEqual(expected, valid);
}
This parameterized tests are somehow confusing at first but the trick is to provide a test method (the above) with both input and output/expected parameters. Note that data types of the [TestCase]
attributes and the method parameters (that is, double and bool) must match and we test both valid and invalid values.
For more advanced parameterized tests you can look at the [TestCaseSource] and [ValueSource] attributes in the NUnit docs.
If you face with a combinatorial explosion with your parameters, look at the [Values], [Random] and [Range] attribues.