2

I'm trying to customize the data that is generated in a class .. where a property is another class.

eg.

public class Foo
{
   public string Id { get; set; }
   public Baa Baa { get; set; }
}


public class Baa
{
   // 30 properties which are strings, ints, etc.
}

I was wondering if i could do something like this...

var fixture = new Fixture();
return fixture.Build<Foo>()
    .With(x => x.Id, $"Foo-{fixture.Create<int>()}")
    .With(x => x.Baa, CreateSomeCustomBaaUsingAutofixture)
    .Create();

and then ..

private Baa CreateSomeCustomBaaUsingAutofixture()
{
    var fixture = new Fixture();
    return fixture.Build<Baa>()
        .With(lots of customizations here)
    .Create();
}

Is there a cleaner way of doing this? Or is .. that basically the only/recommended way?

I understand that AutoFixture can automatically create an instance of a Baa for me and data for the properties in there. I was just hoping to just customize it a bit more.

Pure.Krome
  • 84,693
  • 113
  • 396
  • 647

1 Answers1

4

Since you want to configure Baa by convention, you can simply do that. It might look like this:

fixture.Customize<Baa>(c => c
    .With(x => x.Baz, "Corge")
    .With(x => x.Qux, "Garply"));

Whenever you create a Foo object, the Baa property will have a value created according to those rules:

var foo = fixture.Create<Foo>();
Console.WriteLine(foo.Baa.Baz);
Console.WriteLine(foo.Baa.Qux);

Prints:

Corge
Garply
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • How does the `fixture.Create();` know about how to create the `Baa`? is it because it's the same fixture instance AND the `fixture.Customize....` comes first... Can you update the code to highlight that? (if that's what you mean) ? plz sir? – Pure.Krome Feb 05 '16 at 12:54
  • Kewl - I think i get it now. I made this .NET fiddle: https://dotnetfiddle.net/MqneEZ ... So i create the fixture, define my customizations ... then do the `Create` at the end? – Pure.Krome Feb 05 '16 at 12:59
  • 1
    @Pure.Krome That's correct. Bonus info: if you do a lot of this, you should [encapsulate your customizations](http://blog.ploeh.dk/2011/03/18/EncapsulatingAutoFixtureCustomizations). – Mark Seemann Feb 05 '16 at 13:02