Reputation: 118
Is there a way to redirect the original program output to XUnit output?
All i could find is how to print output from XUnit tests (see here)
With "original output" i mean that for each time i write Console.WriteLine
or similar in my program i want that output to be there when i look at test results.
I know that it is possible to redirect console output to a different textwriter (source), how can i set up my tests so that all output is redirected to Xunit?
Upvotes: 3
Views: 1217
Reputation: 5858
This is a little work but it is achievable.
Like you mentioned, you came across ITestOutputHelper
. With a bit more effort, you can redirect the Console
output to a new class that implements the TextWriter
.
So from this, if you put together something like:
public class RedirectOutput : TextWriter
{
private readonly ITestOutputHelper _output;
public RedirectOutput(ITestOutputHelper output)
{
_output = output;
}
public override Encoding Encoding { get; } // set some if required
public override void WriteLine(string? value)
{
_output.WriteLine(value);
}
}
And in you test constructor (which I suspect the piece you are missing?):
public class UnitTest1
{
public UnitTest1(ITestOutputHelper output)
{
Console.SetOut(new RedirectOutput(output));
}
...
}
This is where we are doing a redirect from the Console
to ITestOutputHelper
.
The downside of this is that you will NEED to override EVERY use of a Console
.Write call you use in your code. So RedirectOutput
can end up quite large. See ms docs here for a list overloads.
I don't know of any other way - I would have hoped it would be simpler. Surely there is another solution somewhere.
But at least this will get you going, if you havent already.
Also might be worth a rethink of design around using Console writes in your code. Perhaps something around a custom interface output?
Upvotes: 3