Jakubee
Jakubee

Reputation: 634

TestContext properties throws NullReferenceException under NUnit3

This used to work ok with old version of nunit.framework.dll. I recently updated my tests to run with SpecRun. When code reaches my BeforeScenario method:

[BeforeScenario]
    public void Init()
    {
        _sw.Start();
        Initialize();

        var env = ConfigManager.GetEnvironment();

        ArrayList categories = TestContext.CurrentContext.Test
   .Properties["Category"] as ArrayList;            // exception here
        if (env.Contains("csp-dev") || env.Contains("csp-qa") || env.Contains(":8445"))
        {
            if (categories != null && categories.Contains(CategoryToExclude))
            {
                Assert.Inconclusive("You tried to run 'Write' test on {0}. Test has been stopped.", env);
            }

        }

        LoginPage.Goto();
        LoginPage.LoginAs(TestConfig.Username).WithPassword(TestConfig.Password).Login();
    }

it throws exception for TestContext properties.

Anyone know work around this under new nunit.dll ?

EDIT: NUnit Version 3.2.1 Re-Sharper 9 VS: 2015 Update 2

Upvotes: 0

Views: 923

Answers (1)

Charlie
Charlie

Reputation: 13681

The expression

TestContext.CurrentContext.CurrentTest.Properties["Category"] as ArrayList

Is always going to be null unless the underlying implementation of NUnit uses an ArrayList - and I can guarantee you it doesn't! The safest way to code this is to write...

var categories = TestContext.CurrentContext.CurrentTest.Properties["Category"];

In the current implementation, this will give you an IList.

I do notice that this interface forces you to know more about NUnit internals than you should have to. You need to know that Categories are implemented as Properties with a specific name. That's OK for our internal code but we should probably add a Categories property to the CurrentTest.

Upvotes: 1

Related Questions