Here’s an example of how to parameterize your tests using the built-in MSTest v2 test framework:
[DataRow(BirdType.Cardinal, 8.0, 9.0)]
[DataRow(BirdType.Goldfinch, 4.5, 5.5)]
[DataRow(BirdType.Chickadee, 4.75, 5.75)]
[DataTestMethod]
public void GetSizeRange(BirdType birdType, double expectedSizeRangeLower, double expectedSizeRangeUpper)
{
//arrange
var bird = Bird.Create(birdType);
//act
var actual = bird.GetSizeRange();
//assert
Assert.AreEqual(expectedSizeRangeLower, actual.Lower);
Assert.AreEqual(expectedSizeRangeUpper, actual.Upper);
}
Code language: C# (cs)
There are 3 steps:
- Add parameters to your test method.
- Use [DataTestMethod] instead of [TestMethod].
- For each test case, add [DataRow(…)] to pass in the parameters for that test case.
What parameters can you pass in?
You pass in parameters via the DataRow attribute. Since this is an attribute, it only accepts compile-time constants (primitives, arrays, enums).
Therefore you can’t pass in class instances. Instead, you can pass in parameters and use them to build the object in the test method.
For example, because I can’t pass in a BirdSizeRange object, I have to pass in the expectedSizeRangeLower and expectedSizeRangeUpper parameters. Then in the test I can construct the BirdSizeRange from these parameters.
public void GetSizeRange(BirdType birdType, double expectedSizeRangeLower, double expectedSizeRangeUpper)
{
//arrange
var bird = Bird.Create(birdType);
BirdSizeRange expectedRange = new BirdSizeRange()
{
Upper = expectedSizeRangeLower,
Lower = expectedSizeRangeUpper
};
//act
var actual = bird.GetSizeRange();
//assert
Assert.AreEqual(expectedRange, actual);
}
Code language: C# (cs)