Ivan Zyranau
Ivan Zyranau

Reputation: 941

How to create new instances of objects with custom SpecimenBuilder with AutoFixture

Currently I have such code:

private ConnectedClient WithConnection(IConnection connection)
{
    var builder = new ClientWithConnectionSpecimenBuilder(connection);

    Fixture.Customizations.Add(builder);
    var client = Fixture.Create<ConnectedClient>();
    Fixture.Customizations.Remove(builder);

    return client;
}

Basically I need to create new instances of ConnectedClient class in my tests code with specified connection. And I've built custom specimen builder to do it.

But there is no method like

Fixture.Create<T>(specimenBuilder) 

so I need to customize the fixture.

"Fixture" there is the inherited protected property of my base tests class that is already set up with some custom AutoMoqData customization so I need to reuse it for creating objects.

Upvotes: 1

Views: 1918

Answers (1)

Jeff Dammeyer
Jeff Dammeyer

Reputation: 666

It should be possible to use the one-off Build method to customize using a particular specimen builder:

var client = fixture.Build<ConnectedClient>().FromFactory(builder).Create();

Note that doing this will disable any other customizations from the fixture.

The DSL supports a bit more customization using With and Without, so if there's some additional customization you want to do on properties, you can do that:

var client = fixture.Build<ConnectedClient>()
    .FromFactory(builder)
    .With(cc => cc.SomeProperty, () => fixture.Build<T>().FromFactory(otherFactory).Create())
    .Create();

But that will get pretty tedious for significant customization. Autofixture is opinionated in this way.

The Build method is really intended as a one-off solution. If you want to rely more on the machinery of Autofixture to do everything except for creating the client connection, I would suggest relying on the existing Freeze method and Frozen attribute to keep the injected IConnection the same for a given ConnectedClient, which would obviate the need for a specific ISpecimenBuilder.

Upvotes: 1

Related Questions