Ignore Test or TestFixture based on a condition

Viewed 19167

We've got some integration tests in our solution. To run these tests, simulation software must be installed on the developer PC. This software is, however, not installed on every developer PC. If the simulation software is not installed, these tests should be skipped, otherwise ==> NullRefException.

I'm now seeking for a way to do a "conditional ignore" for tests/testfixtures.

Something like

if(simulationFilesExist)
  do testfixture
else 
  skip testfixture

NUnit gives some useful things like ignore and explicit, but that's not quite what I need.

5 Answers

I didn't want to duplicate Assert.Ignore condition in every test case, so I ended up using a custom Attribute class, which I derived from the NUnitAttribute class:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class SimulatorOnlyAttribute : NUnitAttribute, IApplyToTest
{
    public void ApplyToTest(Test test)
    {
        if (test.RunState == RunState.NotRunnable)
        {
            return;
        }

        if (!Helper.RunsOnSimulator)
        {
            test.RunState = RunState.Ignored;
            test.Properties.Set(PropertyNames.SkipReason, "This test should run only on simulator");
        }
    }
}

So now I can just mark required test cases with the new attribute:

[SimulatorOnly]
public void Test()

For reference you could investigate source code of the IgnoreAttribute.

There are a lot of ways to alter the result status of a test. Here are a few, and ways to read out the various status:

TestExecutionContext.CurrentContext.CurrentTest.MakeInvalid("I want this test to be SKIPPED");

ResultState resultStateObject = new ResultState(TestStatus.Skipped);
TestExecutionContext.CurrentContext.CurrentResult.SetResult(resultStateObject, "this test is being skipped derp derp");
TestExecutionContext.CurrentContext.CurrentTest.RunState = RunState.Ignored;
Logger.log("After doing things");

resultstate = TestExecutionContext.CurrentContext.CurrentResult.ResultState.ToString();
Logger.log("%%%%%%%%%%%%%%%%%% Result State: " + resultstate);

resultstatestatus = TestExecutionContext.CurrentContext.CurrentResult.ResultState.Status.ToString();
Logger.log("%%%%%%%%%%%%%%%%%% Result State Status: " + resultstate);

runstate = TestExecutionContext.CurrentContext.CurrentTest.RunState.ToString();
Logger.log("%%%%%%%%%%%%%%%%%% Run State: " + runstate); //test="@runstate = 'Skipped' or @runstate = 'Ignored' or @runstate='Inconclusive'

status = TestContext.CurrentContext.Result.Outcome.Status.ToString();
Logger.log("%%%%%%%%%%%%%%%%%% Result Status: " + status);

message = TestExecutionContext.CurrentContext.CurrentResult.Message.ToString();
Logger.log("%%%%%%%%%%%%%%%%%% Message: " + message);
Related