2016-02-05 40 views
1

我試圖自定義類中生成的數據..其中一個屬性是另一個類。如何使用AutoFixture爲屬於類的屬性生成數據?

例如。

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


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

我在想,如果我可以做這樣的事情......

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

然後..

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

是否有這樣做的更清潔的方式?或者......基本上是唯一/推薦的方式?

我知道AutoFixture可以自動爲我創建一個Baa的實例,併爲其中的屬性創建數據。我只是希望稍微定製它。

+0

相關: http://stackoverflow.com/q/27815288/126014 –

+0

可能相關:http://stackoverflow.com/a/5398653/126014 –

+0

你需要'Baa'是按照慣例定製,還是需要爲每個測試用例配置不同的配置?按照慣例定製的 –

回答

1

由於您想按照慣例配置Baa,您可以簡單地這樣做。這可能是這樣的:

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

每當創建Foo對象時,Baa屬性將根據這些規則創建的值:

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

打印:

Corge 
Garply 
+0

'fixture.Create ();'知道如何創建'Baa'?是因爲它是同一個燈具實例,而'fixture.Customize ....'是第一個...你能更新代碼來突出顯示嗎? (如果這就是你的意思)? PLZ先生? –

+0

Kewl - 我想我現在得到它。我做了這個.NET小提琴:https://dotnetfiddle.net/MqneEZ ...所以我創建燈具,定義我的自定義...然後在最後做'創建'? –

+0

@ Pure.Krome沒錯。獎勵信息:如果你做了很多這樣的事情,你應該[封裝你的自定義](http://blog.ploeh.dk/2011/03/18/EncapsulatingAutoFixtureCustomizations)。 –

相關問題