Say I have the following:
[Test]
// would like to parameterize the parameters in call AND the call itself
public void Test()
{
var res1 = _sut.Method1(1);
var res2 = _sut.Method2("test");
var res3 = _sit.Method3(3);
Assert.That(res1, Is.Null);
Assert.That(res2, Is.Null);
Assert.That(res3, Is.Null);
}
I'd like to parameterize the tests using the TestCase/TestCaseSource attribute including the call itself. Due to the repetitive nature of the tests, each method needs to be called with slightly different parameters, but I need to be able to tag a different call for each of the different parameters. Is this even possible in Nunit? If so, how would I go about it?
Using TestCaseSource, you should be able to loop over an array of values and invoke the desired methods, for example like this:
[TestFixture]
public class TestClass
{
private Sut _sut;
public TestClass()
{
_sut = new Sut(...);
}
private IEnumerable<object> TestCases
{
get
{
var values = new object[,] { { 1, "test", 3 }, { 2, "hello", 0 }, ... };
for (var i = 0; i < values.GetLength(0); ++i)
{
yield return _sut.Method1((int)values[i,0]);
yield return _sut.Method2((string)values[i,1]);
yield return _sut.Method3((int)values[i,2]);
}
}
}
[TestCaseSource("TestCases")]
public void Test(object val)
{
Assert.That(val, Is.Null);
}
}
Note that the _sut
instance needs to be instantiated in the TestClass
constructor. It is not sufficient to initialize it within a [SetUp]
or [TestFixtureSetUp]
method.
In case you need different _sut
instantiations for different method invocations, you could create a collection of Sut
instances in the constructor, and access the relevant Sut
item within the for
loop of the TestCases
getter. Alternatively, you could even loop over all Sut
items in the getter...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With