Is there a way to run a list of different action methods for an object in Nunit using TestCase?

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 would like to parameterize the tests using the TestCase / TestCaseSource attribute, including the call itself. Due to the repeatability of the tests, each method needs to be called with slightly different parameters, but I need to be able to mark a different call for each of the different parameters. Is this possible in Nunite? If so, how do I do this?

+6
source share
2 answers

Using TestCaseSource , you should be able to iterate over an array of values ​​and call the necessary methods, for example:

 [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 must be created in the TestClass constructor. It is not enough to initialize it in the [SetUp] or [TestFixtureSetUp] .

If you need different _sut instances for different method calls, you can create a collection of Sut instances in the constructor and access the corresponding Sut element in the for TestCases getter loop. In addition, you can even Sut over all Sut elements in getter ...

+5
source

Afaik, in NUnit there is no such built-in mechanism. However, if there are several methods in the test, I think it would be better to separate them into separate tests.

Provided that you always call these methods on the same object ( _sut ), you can do this with reflection (also if you decide to take the overhead).

For example, add a string parameter to your TestCaseSource, and in the test method, call it like this:

 Type type = _sut.GetType(); MethodInfo methodInfo = type.GetMethod(methodName); object result = methodInfo.Invoke(_sut, null); 

Things will get complicated quickly if each method you want to parameterize will take a different number of arguments. Debugging and detecting a failed test will also be much more difficult. It’s best to separate these tests.

0
source

Source: https://habr.com/ru/post/919309/


All Articles