Wednesday, 27 January 2016

Unit Test (#3) : Passing complex parameters

Last time we talked about common cases in unit test (exception, interface, ...). Today, we will learn how to pass a complex object to the test case.

The test case problem

As you know, xUnit allow us to create the test case by putting data in the [InlineData] attribute.
[Theory]
[InlineData(2,3,5)]
[InlineData(3,3,7)]

However, the [InlineData] just accept data whose type is primitive or simple (like int, string, double...). So if you wanna put some complex parameters (like DateTime, List, ...) to your test case, you must write it in the other way.

Let’s take an example !

Suppose that we have a function which is used to check if a specific day is Saturday or not :
bool isSaturday(DateTime dt)
{
   string day = dt.DayOfWeek.ToString();
   return (day == "Saturday");
}
To test it, we can not write :
[Theory]
[InlineData(new DateTime(2016,1,23), true)]
[InlineData(new DateTime(2016,1,24), false)]
public void test(DateTime dt, bool expected)
{
   bool result = isSaturday(dt);
   result.Should().Be(expected);
}

Solution

In this situation, we will create another class called TestCase.cs to hold the test data. Here it goes:
public class TestCase
{
   public static readonly List<object[]> IsSaturdayTestCase = new List<object[]>
   {
      new object[]{new DateTime(2016,1,23),true},
      new object[]{new DateTime(2016,1,24),false}
   };

   public static IEnumerable<object[]> IsSaturdayIndex
   {
      get
      {
         List<object[]> tmp = new List<object[]>();
            for (int i = 0; i < IsSaturdayTestCase.Count; i++)
                tmp.Add(new object[] { i });
         return tmp;
      }
   }
}
And in the test class, the test function should be like this :
bool isSaturday(DateTime dt)
{
   string day = dt.DayOfWeek.ToString();
   return (day == "Saturday");
}

[Theory]
[MemberData("IsSaturdayIndex", MemberType = typeof(TestCase))]
public void test(int i)
{
   // parse test case
   var input = TestCase.IsSaturdayTestCase[i];
   DateTime dt = (DateTime)input[0];
   bool expected = (bool)input[1];

   // test
   bool result = isSaturday(dt);
   result.Should().Be(expected);
}
Finally, we got it !

For more information about xUnit, please visit http://xunit.github.io.
Thank you !

No comments :

Post a Comment