Friday, May 22, 2015

Avoid typos in your [Category] attributes by extending CategoryAttribute

NUnit categories are a great way to categorizing your tests so you can stage your test runs.  For example, I can have a Smoke and Regression set of test cases, and additionally also tag them by features as well.  That way when I run my NUnit tests, I can filter by the set I want, and run just the tests of the features I'm testing.

The Problem

However, one problem with the Category tag is if you're in a team, and each person is typing the same category strings over and over again, you run into the problem of someone doing a typo somewhere along the way that the compiler cannot catch.

   public class SomeTest  
   {  
     [Category("TestSuite.Smoke")]  
     [Category("Feature.UserInfoForm")]  
     [Category("Speed.Fast")]  
     [Description("Test survey form fields are sticky.")]  
     public void PartiallySubmittedFormShouldRemainSticky()  
       ....  

Imagine having hundreds of tests, where that same string gets typed over and over again.

Possible Solution

One solution you can do is use constants contained in a static class,

   public class SomeTest  
   {  
     [Category(TestType.Category.Smoke)]  
     [Category(TestType.Duration.Short)]  
     [Category(TestType.Stability.Stable)]  
     [Description("Test survey form fields are sticky.")]   
     public void PartiallySubmittedFormShouldRemainSticky()  
       ....  

A more elegant way

we can extend the category attribute like this, and use it in a more expressive way that's more appealing to the eyes.
   public static class TestCategory  
   {  
     public class SmokeAttribute : CategoryAttribute  
     {  
       public SmokeAttribute() : base("TestCategory.Smoke")  
       {  
       }  
     }  
     public class SmokeRegression : CategoryAttribute  
     {  
       public SmokeRegression()  
         : base("TestCategory.Regression")  
       {  
       }  
     }  
   }  

It will look a bit cleaner in usage, and makes your test code look like something less improvised.

   public class SomeTest  
   {  
     [TestCategory.Smoke]  
     [Stability.Stable]  
     [Speed.Short]  
     [Description("Test survey form fields are sticky.")]  
     public void PartiallySubmittedFormShouldRemainSticky()  
       ....  

No comments: