简体   繁体   中英

Accessing value from TestFixture in TestCaseSource (NUnit)

Let's have this setup:

[TestFixture(10)]
[TestFixture(20)]
public class TestClass
{
    int I;

    public TestClass(int i)
    {
        I = i;
    }

    [TestCaseSource(typeof(TestSource))]
    public void Test(string name)
    {
        TestContext.WriteLine(name);
    }

    class TestSource : IEnumerable<TestCaseData>
    {
        public IEnumerator<TestCaseData> GetEnumerator()
        {
            yield return new TestCaseData("AAA") { TestName = $"Test" };                
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

Is there a way to somehow get the current TestFixture value ( 10 or 20 in this case) when generating tests in TestCaseSource (either using class or method, doesn't matter for me)? I know I can workaround that by ie deriving classes or duplicating the methods, but I hope for clean solution (before queuing plan B).

Sorry to say that this can't work. :-(

First of all, let's be clear that your nested testcasesource class has no special standing with NUnit due to it's being nested. It is instantiated independently of the test fixture class and works exactly as it would work if it were not nested.

Here is the sequence of things at test discovery time:

  1. NUnit identifies your test fixture and takes note of the fact that it is will (later) be instantiated twice. It notes the arguments for naming purposes. This gives us two fixtures, each of which needs to have its tests discovered.

  2. NUnit looks at all the methods in each fixture to find tests. When it comes to the TestCaseSourceAttribute, it instantiates the source class and uses it's IEnumerable interface to acquire test cases.

Later (seconds, minutes, years?) NUnit executes your tests. When it reaches the fixture in question, it instantiates it twice, once using 10, and once with 20. The test cases which were previously identified are run.

As you can see, the test fixture is not even instantiated at the time the tests are discovered. Of course, NUnit "knows about" the arguments and theoretically could provide some sort of substitution facility, but no such facility exists - and it would be very complicated to create since in general it could involve simulating arbitrary execution of the fixture's methods.

Storing the value of the argument in the constructor and accessing it from the test is the "standard" way of solving this problem. If there is something you want to do that won't work using that technique, it would be best to spell it out more clearly so we can see if there is workaround.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM