Search code examples
c#unit-testingnunit

How to fetch test category in test setup method


Below is code where test setup method is link with same namespace and all other unit test cases are applied. I want to skip particular unit test case to call test setup method. To achive that, applied category attribute but, its not able to fetch in setup method and all time giving 0 value for Properties['_CATEGORIES'].

    class 1
   {
    [Setup]
    public void SetupMethod()
    {
      if (CheckForSkipSetup()) return;
         ...
    }
    private static bool CheckForSkipSetup() {
        ArrayList categories = TestContext.CurrentContext.Test
           .Properties["_CATEGORIES"] as ArrayList;

        bool skipSetup = categories != null && categories.Contains( SKIP_SETUP );
        return skipSetup ;
    }
   } 
    class 2
    [Test]
    [Category("skipMethod")]
    public void Method1()
    {
    }

How to resolve this issue so, i can get category attribute in setup class.


Solution

  • Upgrade to the latest version of NUnit 3, it is fixed there. The property key is Category.

    For example, the following code,

    [SetUp]
    public void Setup()
    {
        var cats = TestContext.CurrentContext.Test?.Properties["Category"];
        foreach (var cat in cats)
        {
            TestContext.WriteLine("Category: " + cat);
        }
    }
    
    [Test]
    [Category("One")]
    [Category("Two")]
    public void TestMethod()
    {
        Assert.Pass("Passes");
    }
    

    Produces the output,

    Category: One
    Category: Two