Friday, February 5, 2016

NUnit TestCase Attribute

The other day I showed how to use NUnit's TestCaseSource attribute to use a single test to run multiple cases.  Unfortunately, in my haste to get that post up I used a really bad example for it.  Let me refresh your memory.  Imagine we have a method that accepts three strings and returns one:

   1:  public string GetFullName(string firstName, string lastName, string middleName)
   2:  {
   3:      throw new NotImplementedException();
   4:  }

There's a really easy way to pass multiple cases to this method without using TestCaseSource.  You can just use the TestCase attribute.  If our test looks like this:

   1:  [Test]
   2:  public void GetFullName_ShouldConcatenateFirstMiddleAndLastWhenAllThreeHaveValues()
   3:  {
   4:      // arrange
   5:      var program = new Program();
   6:   
   7:      // act
   8:      var fullName = program.GetFullName("Jumping", "Flash", "Jack");
   9:   
  10:      // assert
  11:      Assert.AreEqual("Jumping Jack Flash", fullName);
  12:  }

We can change it to look like this, and it will run two separate tests:

   1:  [Test]
   2:  [TestCase("Jumping", "Flash", "Jack", "Jumping Jack Flash", "ShouldConcatenateFirstMiddleAndLastWhenAllThreeHaveValues")]
   3:  [TestCase("", "Flash", "Jack", "Jack Flash", "ShouldConcatenateMiddleAndLastWhenFirstIsEmptyString")]
   4:  public void GetFullName_ShouldMapNameCorrectly(string firstName, string lastName, string middleName, string expectation, string errorMessage)
   5:  {
   6:      // arrange
   7:      var program = new Program();
   8:   
   9:      // act
  10:      var fullName = program.GetFullName(firstName, lastName, middleName);
  11:   
  12:      // assert
  13:      Assert.AreEqual(expectation, fullName, errorMessage);
  14:  }

This is effectively the same thing as we saw the other day, but when you have simple types as all of your parameters, this is easier.  TestCaseSource really comes into play when you want to pass in a complex object as a parameter.  I'll try to post an example of that soon.

No comments:

Post a Comment