Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

nunit

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?

like image 672
jaffa Avatar asked Jun 29 '12 09:06

jaffa


1 Answers

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...

like image 113
Anders Gustafsson Avatar answered Oct 19 '22 09:10

Anders Gustafsson