Autofixture: Access to fixture created by AutoData attribute.

Created on 25 Apr 2018  ·  7Comments  ·  Source: AutoFixture/AutoFixture

Hi,
For now i only can access the fixture like this.

[Theory, AutoData]
public void Dummy(string dummy)
{
    MethodBase method = MethodBase.GetCurrentMethod();
    IFixture fixture = method.GetCustomAttribute<AutoDataAttribute>().Fixture;


    Assert.Equal(dummy, dummy);
}

And I get the 'AutoDataAttribute.Fixture' is obsolete warning.

Is there a better way to access the fixture created in the AutoData attribute. I would like to mix parameter and manual creation and injection.
Thanks

question

Most helpful comment

Yes, it's really a better way.

Can you put this in the AutoData wiki?
I have searched everywhere to find how to do this.
Did not think the IOC container got the IFixture registered.

Thanks a lot!

All 7 comments

Hi,

Sure, simply ask underlying fixture to resolve IFixture instance and it will return self:

c# [Theory, AutoData] public void Dummy(string dummy, IFixture fixture) { }

Does it work for you? :wink:

Yes, it's really a better way.

Can you put this in the AutoData wiki?
I have searched everywhere to find how to do this.
Did not think the IOC container got the IFixture registered.

Thanks a lot!

Why are you trying to register for the fixture with the IoC? In my experience it is never needed

Mostly to minimize test method parameters for complex recurring interfaces setup.

[Theory, AutoMoqData]
public void Dummy(IFixture fixture, [Frozen]Mock<IComplexInterfaceWith30SubInterfaces> needed, TestClass sut)
{
    //This will add interfaces setups for needed by retrieving them from the IoC container or by property access.
    SetupInterfaces(fixture, needed);
    //We can now use needed injected in sut.
}

I've got a simpler example

I you prefer this

[Theory, AutoMoqData]
public void Dummy(IFixture fixture)
{
    Assert.Equal(String.Empty, String.Empty);
}

over this

[Fact]
public void Dummy2()
{
    IFixture fixture = new Fixture().Customize(new AutoMoqCustomization());

    Assert.Equal(String.Empty, String.Empty);
}

Mostly to minimize test method parameters for complex recurring interfaces setup.

Agree, I have the similar usage in tests. The only difference is that I prefer to prefix those auxiliary repeating methods with When(), so test looks like following:

c# public void Test([Frozen] IProvider provider, ISut sut, IFixture fixture) { // arrange WhenProviderReturnsOnlyInitializedEntities(provider, fixture); ..... }

But basically idea is still the same 😉

Closing this one as no more actions are required.

Can you put this in the AutoData wiki?

@malylemire1 I'm going to create a doc site somewhere in future. However, feel free to add this sample to our wiki 😅

Was this page helpful?
0 / 5 - 0 ratings