Hi,
I'm using MSTest for testing and when I want to apply more inputs then the test looks like this:
[TestMethod]
public void SumTest()
{
// data to test
var items = new [] {
new { First = 1, Second = 1, Expected = 2 },
new { First = -1, Second = 1, Expected = 0 },
new { First = 1, Second = 2, Expected = 3 },
new { First = 1, Second = -1, Expected = 0 },
};
ICalculator target = GetSum(); // can be in the loop body
foreach(var item in items)
{
var actual = target.Sum(item.First, item.Second);
Assert.AreEqual(item.Expected, actual);
}
}
I feel that this kind of testing is not the right way. I.e. I would like to separate testing data generation and testing itself.
I know, there is "data driven test" support in MSTest but it isn't sufficient for me:
- The
items
collection cannot be generated using some algorithm. - I cannot use non-primitive types.
So what is your suggestion for this kind of tests?
I would like to have something like this but I'm not sure if this is the right way and if some testing framework supports this scenario.
[TestData]
public IEnumerable<object> SumTestData()
{
yield return new { First = 1, Second = 1, Expected = 2 };
yield return new { First = -1, Second = 1, Expected = 0 };
yield return new { First = 1, Second = 2, Expected = 3 };
yield return new { First = 1, Second = -1, Expected = 0 };
}
[TestMethod(DataSource="method:SumTestData")]
public void SumTest(int first, int second, int expected)
{
// this test is runned for each item that is got from SumTestData method
// (property -> parameter mapping is no problem)
ICalculator target = GetSum();
var actual = target.Sum(first, second);
Assert.AreEqual(expected, actual);
}