Search code examples
frameworksnunit

Is there any alternative to [OneTimeSetup] in Nunit?


In my existing [OneTimeSetup] method, I want to check some preconditions before running any test. But I can't do so as the object which I'll be needing to check preconditions is initialized in Base class [Setup] method. I can't initialize this earlier due to some project limitations. So, Is there any way where I can execute some code after Base [Setup] method (to check some preconditions) and before any suite execution? I want to execute this once per suite.

[SetUpFixture]
Class GlobalSetup
{
   [OneTimeSetUp]
   public void OneTimeSetUp(){
      setup();
      CheckIfDataIsPresent();   // I can't do this here as this code needs Obj O to be initialized. which will be initialized in Base class's [Setup] methed
   }
}

Public class Base
{
   [Setup]
   public void setUp()
   {
      //some code where we initialize obj O; 
   }
}

[TestFixture]
public class Test : Base
{
   // tests to be executed
}


Solution

  • You already did a nice job of explaining why what you want to do won't work, so I don't have to. :-)

    The problem is that each your tests needs a fresh instance of that object, so you properly create it in a [SetUp] method. You would like to ensure that it's possible to create such an object once before you run any tests.

    I can only give you a non-specific answer, since you haven't given a lot of info in your example code. If you update your question, I may be able to update my answer. Here goes...

    1. Both your tests and the check you want to perform require an instance of object o. So one approach would be to initialize o one more time in the OneTimeSetup, perform the check and then throw it away. Since you are initializing o in every test, I assume it's not expensive to do so. Say you have 100 tests. You are setting up o 100 times. So make it 101 and be done!

    2. Alternatively, determine what is required for o to be initialized successfully and check that. For example, if it needs a file to be present, check that the file is present. If the file has to have 100 records in some format, check that it's so. Perhaps you might give us more detail about what those prerequisites are.

    3. Finally, you might reconsider whether you really need a new instance per test. Since you suggest you would be willing to make a check once per fixture (I assume that's what you mean by suite) then perhaps you really only need one instance per fixture rather than a new one for each test.