Search code examples
c#unit-testingxunitxunit.netxunit2

xUnit test suite where inner class can access outer class' data


I have some large test suites so I broke them into inner/nested classes. That also makes the results in the VSCode test explorer more friendly.

But it doesn't work well when there's common fixture data that's defined in the outer class:

public class UserTests
{
  // common fixture data used by all inner classes
  public UserTests() => _fake = new Fake();
  private readonly Fake _fake;

  public class AddUser {

    public AddUser(UserTests o) => _outer = o;
    private readonly UserTests _outer;

    [Fact]
    public void test_foo() {
      // use _outer._fake
    }

    [Fact]
    public void test_bar() {
      // use _base._fake
    }
  }

  public class FindUser 
  {
    // ...similar to above
  }

  public class DeleteUser {
    // ...similar to above
  }
}

But I get this error:

The following constructor parameters did not have matching fixture data: UserTests o

So maybe the above is a bad setup.

What's a good setup that allows me to have nested classes and also create fixture data in the outer class, so it can be used by all inner classes?


Solution

  • As explained by @Fabio in comments above, the test runner doesn't know how to instantiate the test classes.

    So the trick is to call _outer = new UserTests() in the inner class' constructor.