Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to have ITestOutputHelper created by xUnit to be available in AutoFixture context?

Is is possible to have ITestOutputHelper created by xUnit to be available in AutoFixture context?

In my integration tests I use Builder class that contains helper methods for some routine operations. In order to hide complexity of class creation I use custom AutoDataAttribute, so my tests are getting created object as test method parameter from AutoFixture.

Now I decided to add some logging functionality to Builder and can't find out how to pass ITestOutputHelper into Builder constructor from custom AutoDataAttribute.

using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoNSubstitute;
using Ploeh.AutoFixture.Xunit2;
using Xunit;
using Xunit.Abstractions;

namespace XunitAutoFixtItestOutput
{
    public class Class1Tests
    {
        private readonly ITestOutputHelper _output;

        public Class1Tests(ITestOutputHelper output)
        {
            _output = output;
        }

        [Theory, DefaultAutoData]
        public void UnitOfWork_StateUnderTest_ExpectedBehavior(Builder builder)
        {
        }
    }

    public class Builder
    {
        private readonly ITestOutputHelper _outputHelper;

        public Builder(ITestOutputHelper outputHelper)
        {
            _outputHelper = outputHelper;
        }

        public void DoSomething()
        {
            _outputHelper.WriteLine("Something happened");
        }
    }

    public class DefaultAutoData : AutoDataAttribute
    {
        public DefaultAutoData() : base(new Fixture().Customize(new DefaultCustomization()))
        {
            this.Fixture.Customize<Builder>(f => f.FromFactory(new Builder(??Where to get it from??)));
        }
    }

    public class DefaultCustomization : CompositeCustomization
    {
        public DefaultCustomization() : base(new AutoConfiguredNSubstituteCustomization())
        {
        }
    }
}
like image 448
Michael Baranov Avatar asked Feb 11 '17 21:02

Michael Baranov


1 Answers

As Mark Seemann foresaw in the comments, it's not supported in the current version (v2.1) and there is no visible extensibility point. Therefore, it might be added in future versions.

There is a suggestion to sacrifice the AutoData attribute (at least until xUnit is extended) and configure fixture in the test constructor:

public class Class1Tests
{
  private readonly Fixture fixture;

  public Class1Tests(ITestOutputHelper output)
  {
    this.fixture = new Fixture();
    this.fixture.Inject(output);
  }

  [Fact]
  public void UnitOfWork_StateUnderTest_ExpectedBehavior()
  {
    var builder = this.fixture.Create<Builder>();
    builder.DoSomething();
  }
}
like image 141
Serhii Shushliapin Avatar answered Sep 20 '22 11:09

Serhii Shushliapin