Reputation: 360
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?
Upvotes: 3
Views: 3457
Reputation: 13736
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...
[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.
Upvotes: 4