作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想使用 AutoFixture
创建自定义对象列表.我要第一个N
对象将一个属性设置为一个值,其余的将其设置为另一个值(或简单地由 Fixture
的默认策略设置)。
我知道我可以使用 Fixture.CreateMany<T>.With
,但这会将函数应用于列表的所有成员。
在NBuilder
有名为 TheFirst
的方法和 TheNext
(除其他外)提供此功能。它们的使用示例:
给定一个类 Foo
:
class Foo
{
public string Bar {get; set;}
public int Blub {get; set;}
}
一个人可以实例化一堆Foo
就像这样:
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
实现此目的的“内置”方法? ?还是一种惯用的方式来设置夹具以表现得像这样?
最佳答案
到目前为止,最简单的方法是这样的:
var foos = fixture.CreateMany<Foo>(10).ToList();
foos.Take(5).ToList().ForEach(f => f.Bar = "Baz");
foos.Skip(5).Take(3).ToList().ForEach(f => f.Bar = "Qux");
foos.ForEach(f => f.Blub = 11);
为属性赋值已经内置于 C# 中,因此与其提供限制性 API 可能无法让您做您想做的一切,the AutoFixture philosophy is to use the language constructs already available .
下一个哲学步骤是,如果您经常需要做这样的事情,SUT可能会受益于重新设计。
关于c# - 如何仅对列表中的一部分项目分配属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19286476/
我是一名优秀的程序员,十分优秀!