Showing posts with label ITestOutputHelper. Show all posts
Showing posts with label ITestOutputHelper. Show all posts

Wednesday, June 24, 2015

Capture xUnit Test Output with NLog and Common Logging

I recently blogged about How To Capture Test Output in xUnit 2.0. This is great, but how can we pass the ITestOutputHelper into our code to capture log output?

You could just wrap the xUnit helper in an ILog or ILogger, but we can also take it a step further and get all of the NLog features too! By creating an NLog target that wraps the ITestOutputHelper we can enable ourselves to use multiple targets, layouts, variables, verbosity levels, and more.

Sample Unit Test

public class NLogTests : IDisposable
{
    private readonly ILogger _logger;
 
    public NLogTests(ITestOutputHelper outputHelper)
    {
        _logger = outputHelper.GetNLogLogger();
    }
 
    public void Dispose()
    {
        _logger.RemoveTestOutputHelper();
    }
 
    [Fact]
    public void Hello()
    {
        _logger.Trace("World Trace");
        _logger.Debug("World Debug");
        _logger.Warn("World Warn");
        _logger.Error("World Error");
    }
}

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

Real Time Web Analytics