Skip to content

MartinCostello.Logging.XUnit v0.1.0

Compare
Choose a tag to compare
@martincostello martincostello released this 30 Sep 16:47
bd0a759

MartinCostello.Logging.XUnit v0.1.0

NuGet

Introduction

MartinCostello.Logging.XUnit provides extensions to hook into the ILogger infrastructure to output logs from your xunit tests to the test output.

Installation

To install the library from NuGet using the .NET SDK run:

dotnet add package MartinCostello.Logging.XUnit --version 0.1.0

Usage

using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;

namespace MyApp.Calculator
{
    public class CalculatorTests
    {
        public CalculatorTests(ITestOutputHelper outputHelper)
        {
            OutputHelper = outputHelper;
        }

        private ITestOutputHelper OutputHelper { get; }

        [Fact]
        public void Calculator_Sums_Two_Integers()
        {
            // Arrange
            var services = new ServiceCollection()
                .AddLogging((builder) => builder.AddXUnit(OutputHelper))
                .AddSingleton<Calculator>();

            var calculator = services
                .BuildServiceProvider()
                .GetRequiredService<Calculator>();

            // Act
            int actual = calculator.Sum(1, 2);

            // Assert
            Assert.AreEqual(3, actual);
        }
    }

    public sealed class Calculator
    {
        private readonly ILogger _logger;

        public Calculator(ILogger<Calculator> logger)
        {
            _logger = logger;
        }

        public int Sum(int x, int y)
        {
            int sum = x + y;

            _logger.LogInformation("The sum of {x} and {y} is {sum}.", x, y, sum);

            return sum;
        }
    }
}