3

I'm curious if it is possible to pass local variables as arguments in a TestCase using the NUnit Framework.
Here is an example:

public XDocument config = XDocument.Load(Constants.configFile);

[Test(config)]
public void TestMethod(XDocument xml)
{
    ...
}

Is there any simple solution how I can make this work?

3
  • I normally set them up as members of the test class, perhaps initializing them in a startup method Commented Feb 12, 2021 at 16:32
  • Yes that's possible. But in my case I end up with a few test methods that are very similar. That's where in my opinion a TestCase would do its job. Commented Feb 12, 2021 at 16:37
  • Attributes do not work like that in c# Commented Feb 12, 2021 at 16:48

1 Answer 1

4

As you discovered, you can't do that because C# won't let you use the value of a non-constant object as the argument to an attribute.

But even if the syntax were possible, NUnit couldn't do it because...

  1. The value is initialized when the the class is constructed
  2. The class is not constructed until you run the tests.
  3. NUnit needs the test case argument before you run the tests.

[The last point is what allows NUnit, when used under a GUI runner to display all the tests before you run them.]

The simplest approach to this would be to make config a static member and use it directly from within your tests rather than as an argument. I understand from your comment that this won't work for your situation.

In that case you can solve the problem with a layer of indirection. If you switch from use of TestCase to TestCaseSource, you can use a static method as the source and have that method execute whatever code you desire in order to return the list of values to be used for test cases. For example...

static public IEnumerable<XDocument> Config()
{
    yield return XDocument.Load(Constants.configFile);
}

[TestCaseSource(nameof(Config)]
public void TestMethod(XDocument xml)
{
    ...
}

The source is returning an IEnumerable<XDocument> rather than just an XDocument because TestCaseSourceAttribute is actually intended to return a number of test cases. We're slightly abusing it here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the detailed explanation! I just tried it out and it works fine. It's definitely a good alternative, but sad there is nothing easier that can be used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.