Search code examples
.netunit-testingxunitxunit.net

How to make a test case ignore the constructor in xUnit?


I have a test class that is using In Memory DB. So in the constructor we create the db context and pass it to the service constructor so that we can use this service instance in every test case:

private readonly IService _service;
private readonly Context _context;

public MyTestClass() {
    _context = CreateContext();
    _service = new Service(_context);
}

However, I would like to ignore that constructor setup in one specific test case so that I can populate the context the way I need and instantiate the service with that recently created context for that specific test case. Is it possible?


Solution

  • There is no proper way to get a TestContext that would let you know which test it's for within the constructor.

    Best thing you can do is put another Test Class alongside (could even be in the same file) that houses the single test that needs the different behavior.

    Alternately, if you do change _service to Lazy<IService> and do _service=new Lazy<IService>(() => new Service(CreateContext())), then you can have all but one test trigger the initialization with var service = service.Value` at the start of each test.