Saturday, May 23, 2015

How To Capture Test Output in xUnit 2.0

As of xUnit 2.0 the test framework no longer captures any native outputs, this is by design. Now the question is: where do you write your test output?

You now have to write all test output to an interface, ITestOutputHelper, that is injected into your test's constructor. This design seems to have polarized developers a bit, as not everyone enjoys being require to add a constructor to your test classes. Personally, as a huge fan of dependency injection, I really like this solution.

Spoilers: My next blog post will be about how to combine this with Common.Logging and NLog.

Sample Test

using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
 
namespace XUnitDemo
{
    public class OutputTests
    {
        private readonly ITestOutputHelper _testOutput;
 
        public OutputTests(ITestOutputHelper testOutput)
        {
            _testOutput = testOutput;
        }
 
        [Fact]
        public async Task WriteLine()
        {
            _testOutput.WriteLine("Hello");
            _testOutput.WriteLine("World");
 
            await Task.Delay(1000);
            
            _testOutput.WriteLine("Goodnight");
            _testOutput.WriteLine("Moon");
        }
    }
}

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics