【发布时间】:2013-10-10 03:17:25
【问题描述】:
我想使用AutoFixture 创建一个自定义对象列表。我希望第一个 N 对象将属性设置为一个值,其余的将其设置为另一个值(或简单地由 Fixture 的默认策略设置)。
我知道我可以使用Fixture.CreateMany<T>.With,但这会将函数应用于列表的所有成员。
在NBuilder 中有名为TheFirst 和TheNext(以及其他)的方法提供此功能。它们的使用示例:
给定一个班级Foo:
class Foo
{
public string Bar {get; set;}
public int Blub {get; set;}
}
可以像这样实例化一堆Foos:
class TestSomethingUsingFoo
{
/// ... set up etc.
[Test]
public static void TestTheFooUser()
{
var foosToSupplyToTheSUT = Builder<Foo>.CreateListOfSize(10)
.TheFirst(5)
.With(foo => foo.Bar = "Baz")
.TheNext(3)
.With(foo => foo.Bar = "Qux")
.All()
.With(foo => foo.Blub = 11)
.Build();
/// ... perform the test on the SUT
}
}
这给出了具有以下属性的Foo 类型的对象列表:
[Object] Foo.Bar Foo.Blub
--------------------------------
0 Baz 10
1 Baz 10
2 Baz 10
3 Baz 10
4 Baz 10
5 Qux 10
6 Qux 10
7 Qux 10
8 Bar9 10
9 Bar10 10
(Bar9 和Bar10 值代表NBuilder 的默认命名方案)
是否有使用AutoFixture 的“内置”方法来实现这一点?还是一种惯用的方式来设置一个像这样表现的夹具?
【问题讨论】:
-
Foo类是什么样的? -
@MarkSeemann 我已经使用
Foo扩展了示例,使其更加清晰。如果您指的是我的实际项目中Foo是代理的实际类,则大致相同:只是一个带有gettable/settablestring、int、DateTime字段的POCO。
标签: c# .net unit-testing mocking autofixture