Search code examples
c#nunitfixtures

NUnit - TestFixtureSource executed before SetUpFixture


I have a setupfixture which will update some variables.

[SetUpFixture]
    public class TestSetUp
    {
        [OneTimeSetUp]
        public void Setup()
        {
            var GlobalVar.MSIPath = Path.GetDirectoryName(Directory.GetCurrentDirectory());
        }
    }

And I have a method as part of TestFxtureSource which uses the variables updated by SetUpFixture.

[TestFixture, TestFixtureSource(typeof(GlobalVar), nameof(GlobalVar.ExtractMSIFiles))]
    public class Tests
    {

    }


public static string[] ExtractMSIFiles()
{
   GlobalVar.MSIFiles = Directory.GetFiles(GlobalVar.MSIPath, "*.msi", SearchOption.TopDirectoryOnly); //-----> Error here
}

All the classes are under the same namespace.

But I am seeing the error:

OneTimeSetUp: System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
  ----> System.ArgumentException : The path is empty. (Parameter 'path')

When I debugged this, I see that the TestFixtureSource is executed before SetUPFixture, hence the variable MSIPath is not updated. But my requirement is that SetUPFixture need to be executed first and then TestFixtureSource. What am I missing here?


Solution

  • Here's the sequence of events...

    Test Discovery...

    1. Your test case source is executed., it calls the static method ExtractMSIFiles in order and sets GlobalVar.MSIFiles

    2. ExtractMSIFiles references `GlobalVar.MSIPath, which has not yet been set.

    Test Execution...

    1. Your SetUpFixture runs first. The OneTimeSetupMethod initializes GlobalVar.MSIPath... but it's too late!

    I think the simplest fix is to move the initialization of MSIPath into ExtractMSIFiles.