Jesper Bangsholt
Jesper Bangsholt

Reputation: 534

Using a AutoFixture created mock in a concrete implementation

I have the following issue with regards to AutoFixture, explained in code

public SUT(IConcrete concrete)
{
    DTO BuildDTO()
    {
         return new DTO 
         {
             URL = concrete.GetString(arg1, arg2);
         };
    }
}

public Concrete : IConcrete
{
    public Concrete(ISomeHandler someHandler)
    {
        ...
    }

    public GetString(obj arg1, obj arg2)
    {
        return someHandler.GetUri(arg1, arg2);
    }
}

public void Test(
[Frozen] Mock<ISomeHandler> someHandler,
SUT mySUT)
{
    someHandler.Setup(...);
    mySUT.DoStuff();
    //assert everything went as expected
}

My problem is simply, how do I register the IConcrete with AutoFixture, in such a way that I can access the frozen mock that should be injected into it in the test case?

In actuality, this is about injecting a HttpRequestMessage into a URL Resolver, which is used in a Handler, called from the controller in a Web API project.

I have tried to register the IConcrete with an autofixture created mock

fixture.Register<IConcrete>(new Mock<ISomeHandler>());

but then I cannot access this mock in the unit test and setup the return value.

Thanks in advance for any and all help :)

Upvotes: 1

Views: 358

Answers (1)

Serhii Shushliapin
Serhii Shushliapin

Reputation: 2708

In order to allow AutoFixture generating mocks the AutoMocking Container needs to be enabled.

You need to do the following:

  1. Create the AutoMoqAttribute:

    public class AutoMoqDataAttribute : AutoDataAttribute
    {
      public AutoMoqDataAttribute()
        : base(new Fixture().Customize(new AutoMoqCustomization()))
      {
      }
    }
    
  2. Decorate your test with the new attribute:

    [Theory, AutoMoqData]
    public void Test(
      [Frozen] Mock<ISomeHandler> someHandler,
      Sut sut)
    {
      someHandler.Setup(s => s.DoStuff()).Returns("123");
      Assert.Equal("123", sut.SomeHandler.DoStuff());
    }
    

Where Sut and ISomeHandler are the following:

public class Sut
{
  public Sut(ISomeHandler someHandler)
  {
    SomeHandler = someHandler;
  }

  public ISomeHandler SomeHandler { get; }
}

public interface ISomeHandler
{
  string DoStuff();
}

Upvotes: 3

Related Questions