paulx9000
paulx9000

Reputation: 11

Is it okay to write [Test, OneTimeSetup]?

I wrote [Test,OneTimeSetup] above a test case is that running the OneTimeSetup method I defined again?

We have a heavy setup process that requires us to use a [OneTimeSetup] for Nunit. There was a problem that some of the data would be changed and cause a test case to fail when run in the Test Fixture but not as a Individual test. So above the test I wrote [Test, OneTimeSetup] and that solved the problem.

[OneTimeSetUp]
  public void Initialize()
  {
      //Setup Code        
  }

[Test]
public void TestName1()
{
   ...
}

[Test, OneTimeSetUp]
  public void TestName2()
  {
     //Test Code
  }

Upvotes: 1

Views: 91

Answers (1)

Charlie
Charlie

Reputation: 13736

I think your "fix" changed behavior in a way that no failure is seen but that you did't actually fix a dependency that is messing up your tests.

Here's what happens with the attributes you use.

  1. Because you tricked NUnit to think that TestName2 is a one-time setup method, it runs first thing, before any other tests.

  2. Then TestName1 runs, as the first test found. Although the order is not guaranteed, that's probably the order that's being used, based on your report.

  3. Then TestName2 runs again, this time as a test, because it is marked as a test as well.

However, what you are doing should really be an error in NUnit. A method is either a Test method, SetUp method, TearDown method, etc. It's not intended to be more than one of those things. It would be unsurprising if the next release of NUnit detected what you are doing and gave an error.

A better solution is to analyze your tests to find the ordering dependency and remove it.

Upvotes: 1

Related Questions