我期待定製AutoFixture的創建時行爲,以便在生成並分配燈具的屬性後,我可以設置一些相關對象。AutoFixture可以在創建對象時執行委託嗎?
例如,假設我有一個自定義的方法的User
,因爲它的IsDeleted
屬性總是有成爲一組特定的測試失敗:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsDeleted { get; set; }
}
public static ObjectBuilder<User> BuildUser(this Fixture f)
{
return f.Build<User>().With(u => u.IsDeleted, false);
}
(我手的ObjectBuilder
回測試,因此如果需要,可以進一步定製夾具。)
我想在創建時自動將該用戶與其匿名集合Id
關聯起來,但我不能這樣做,因爲Id
還沒有由我手中產生的時間返回值返回到單元測試的適當位置。這是我想要做的事情:
public static ObjectBuilder<User> BuildUserIn(this Fixture f, UserCollection uc)
{
return f.Build<User>()
.With(u => u.IsDeleted, false);
.AfterCreation(u =>
{
var relation = f.Build<UserCollectionMembership>()
.With(ucm => ucm.UserCollectionId, uc.Id)
.With(ucm => ucm.UserId, u.Id)
.CreateAnonymous();
Repository.Install(relation);
}
}
是這樣的可能嗎?或者有更好的方法來實現我創建匿名對象圖的目標?
你想爲用戶類型的特定實例,並重新使用它的ID屬性值別的地方? – 2012-04-05 19:17:35
這有幫助嗎? http://stackoverflow.com/questions/5398258/customizing-autofixture-builder-with-seeded-property/5398653#5398653 – 2012-04-05 20:32:26
@MarkSeemann:'Do()'顯然可以在對象完全填充之前執行,這樣就不會'工作。我可以(也可以)手動執行示例lambda或做我的對象定製後創建,但我喜歡類似於上面的替代! – ladenedge 2012-04-09 07:31:52