[SOLVED] Problem of Xunit.net TestOutputHelper not working with C# Library project

Issue

TEST ENVIRONMENT:

.NET 6 console app with a class library in C#
Visula Studio 2022
Packages:
Xunit 2.4.2
Xunit.runner.visualstudio 2.4.3

PROBLEM DESCRIPTION:

I was testing output messages to Xunit test result using TestOutputHelper (provided in XUnit.sdk)

The output message works properly when unit tests against objects in console app: XunitCollection.

But, it does not work when testing against objects in class library: ServiceManager (see details in the test output at the end). There is no compiler error. The ServiceManager was added as project reference in ServiceManagerTest.

Why it works when testing against C# console app, but not when testing against class library?

TESTING CODE:

—– Class Randomizer to be tested in IBRARY: SeviceManager —-

{
    public class Randomizer
    {
        public int RndNumber { get; private set; }
        private Random _rnd;
        public Randomizer()
        {
            _rnd = new Random();
            RndNumber = _rnd.Next();
        }

        public void RandomWithRange(int lower, int upper)
        {
            RndNumber = _rnd.Next(lower, upper);
        }
    }
}

—— Unit Test Case ——

using Xunit;
using Xunit.Sdk;

namespace ServiceManagerTests
{
    public class OutputMessageTest
    {
        private TestOutputHelper _outHelper;

        public OutputMessageTest(TestOutputHelper outHelper)
        {
            _outHelper = outHelper;
        }

        [Fact]
        public void WriteMessageTest()
        {
            _outHelper.WriteLine("First Message added to the test result");

            Assert.True(true);
        }
    }
}

—— Output from Failed Test ——

 ServiceManagerTests.OutputMessageTest.WriteMessageTest
  Source: OutputMessageTest.cs line 16
  Duration: 1 ms

  Message: The following constructor parameters did not have matching fixture data: TestOutputHelper outHelper

Solution

You should be injecting the interface ITestOutputHelper, not the concrete class TestOutputHelper into your test fixtures, i.e.

private ITestOutputHelper _outHelper;

public OutputMessageTest(ITestOutputHelper outHelper)
{
    _outHelper = outHelper;
}

[Fact]
public void MyFact()
{
    _outHelper.WriteLine("Foo");
}

XUnit won’t resolve the concrete class, and will likely give you the run time error:

The following constructor parameters did not have matching fixture data: TestOutputHelper outputHelper

Answered By – StuartLC

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *