One Developer
One Developer

Reputation: 566

How can I pass a parameter to the interface IClassFixture<TFixture>?

I am writing a unit test using xUnit for .Net core.

Below is the TestBase Class

public class TestBase : IDisposable
{
    TestBase(string filename) {
        ...
        stream = new MemoryStream(File.ReadAllBytes(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, filename))));
    }
    public TestBase() : this("filename.csv") { }            

    public void Dispose() {
        ..
    }
}

Here's how it's being used

public class FileProcessingServiceFacadeTest : IClassFixture<TestBase>
{
    TestBase testBase { get; set; }

    public FileProcessingServiceFacadeTest(TestBase testBase) {
        this.testBase = testBase;
    }

    [Fact]
    public void ProcessAsync() {
        ....
    }
}

Because I don't know how to pass the parameter to the TestBase class using interface IClassFixture, I had to create a constructor that internally calls the parameter constructor.

Can I pass a parameter to interface IClassFixture without an additional constructor?

Upvotes: 2

Views: 2323

Answers (1)

Ruben Bartelink
Ruben Bartelink

Reputation: 61875

Only default constructors are supported for Class (or Collection Fixtures). The main use cases are covered in the docs.

The interface is solely a marker which the test runner uses to know what it needs to create/dispose for a given Test Class. If the constructor on the Test Class asks for the instances, it gets them supplied; if not, that's fine too (they still get created and Disposed)

In other words, the best you can do is to define a base class and then have a concrete derived class that passes down the filename.

Upvotes: 3

Related Questions