Customizing property value generation

Jun 24, 2011 at 2:18 PM

After some struggle with Entity Framework (see my previous post) I am now explicitly initializing entity properties. I've found an old post with description of TypeMappings, but it seems to be an old syntax, and recent AutoFixture versions use Customize<T> instead.

So I wanted to customize type creation:

            fixture.Customize<MyEntity>(e =>
                e.OmitAutoProperties()
                .With(x => x.EntityId, Guid.NewGuid().ToString()));

Now if I call fixture.CreateAnonymous<MyEntity>() I will get an instance of MyEntity with properly initialized EntityId. But I will get same EntityId also next time - since Guid generator is passed not as a labmda expression but as a generated value, the same value is used every time my test asks about MyEntity instance.

How can I modify the code above to enable generation of anonymous MyEntity instances with different EntityIds?

Coordinator
Jun 25, 2011 at 12:33 PM
Edited Jun 25, 2011 at 12:34 PM

You could use the Do method instead. It allows you to invoke arbitrary code blocks during object creation, but it doesn't 'reserve' the property or field like the With method does. However, combined with OmitAutoProperties or an explicit Without it works fine:

 

fixture.Customize<MyEntity>(e =>
    e.OmitAutoProperties()
        .Do(x => x.EntityId = Guid.NewGuid().ToString()));

 

However, that probably doesn't fix your underlying problem, but I'm going to provide a another answer over at the other discussion


Jun 27, 2011 at 9:15 AM

I see. Yes, this is what I need. Thanks for the tip.