Using xUnit with asp.net, I have isolated some test dependencies in different fixtures that should be global (they perform test setup that can be shared among multiple tests); but on more than one occasion I needed to write some logs on those fixtures to debug certain situations.
A sample is:
public class UnitTest(InterestingFixture f): IClassFixture<InterestingFixture> {
[Fact]
public void Test() {
var data = f.GetData();
// do something with data...
}
}
public class InterestingFixture {
public InterestingFixture() {
// performs some initialization which I want to log to the test output
}
}
In the same above, I want InterestingFixture to get an instance of ITestOutputHelper so that I can write something to the output. I've tried adding ITestOutputHelper to its constructor, but it seems that xUnit isn't injecting anything on the IClassFixtures.
I could manually instantiate InterestingFixture, but it will remove the singleton properties given by xUnit.
How can I accomplish that? Is it supported by xUnit?
I'm on xUnit 2.8.
Not sure if this is exactly what you are trying to accomplish but, your fixture class could store the logs and let your test class print them. Like so:
public class TestFixture : IAsyncLifetime
{
private readonly StringBuilder _sb = new();
public string Logs => _sb.ToString();
public Task InitializeAsync()
{
_sb.AppendLine("Initialising...");
// do something
_sb.AppendLine("Success!");
return Task.CompletedTask;
}
public Task DisposeAsync() => Task.CompletedTask;
}
public class UnitTest : IClassFixture<TestFixture>
{
private readonly TestFixture _fixture;
private readonly ITestOutputHelper _output;
public UnitTest(TestFixture fixture, ITestOutputHelper output)
{
_fixture = fixture;
_output = output;
_output.WriteLine(_fixture.Logs);
}
[Fact]
public void Test1()
{
// your test
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With