Thursday, February 27, 2014

TestCase Attribute (NUnit 2.5)


Have you ever thought how easy would it be if we could pass parameters and expected result to a Unit Test method we have rather writing multiple test methods.
It is possible now with NUnit 2.5 “TestCase” Attribute.

Suppose you have a method to test whether a year is a leap year or not which you want to test by passing different values here is the solution.
 
        [TestCase(2000, Result = true)]
        [TestCase(1996, Result = true)]
        [TestCase(2013, Result = false)]
        public bool IsLeapYearTest(int year)
        {
            return DateTime.IsLeapYear(year);
        }
and if you want to pass multiple parameters just add them comma seperated as below example.
   
        [TestCase(12, 3, Result = 4)]
        [TestCase(12, 2, Result = 6)]
        [TestCase(12, 4, Result = 3)]
        public int DivideTest(int n, int d)
        {
            return (n / d);
        }

This helps us to provide test methods with parameters as well as providing inline date to be used when invoking that method.

Happy Coding

No comments :

Post a Comment