[英]How do I assign a property on only a subrange of items in a list?
I want to create a list of custom objects using AutoFixture
. 我想使用
AutoFixture
创建自定义对象列表。 I want the first N
objects to have a property set to one value, and the remainder to have it set to another value (or to simply be set by the Fixture
's default strategy). 我希望前
N
对象的属性设置为一个值,剩余部分将其设置为另一个值(或者简单地由Fixture
的默认策略设置)。
I am aware that I can use Fixture.CreateMany<T>.With
, but this applies a function to all members of the list. 我知道我可以使用
Fixture.CreateMany<T>.With
,但这Fixture.CreateMany<T>.With
一个函数应用于列表的所有成员。
In NBuilder
there are methods named TheFirst
and TheNext
(among others) which provide this functionality. 在
NBuilder
有命名方法TheFirst
和TheNext
(等等),其提供了这种功能。 An example of their use: 他们使用的一个例子:
Given a class Foo
: 鉴于
Foo
类:
class Foo
{
public string Bar {get; set;}
public int Blub {get; set;}
}
one can instantiate a bunch of Foo
s like so: 一个人可以像这样实例化一堆
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
}
}
This gives a list of objects of type Foo
with the following properties: 这给出了
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
(The Bar9
and Bar10
values represent NBuilder
's default naming scheme) (
Bar9
和Bar10
值代表NBuilder
的默认命名方案)
Is there a 'built-in' way to achieve this using AutoFixture
? 是否有“内置”方式使用
AutoFixture
实现此AutoFixture
? Or an idiomatic way to set up a fixture to behave like this? 或者设置一个像这样的夹具的惯用方法?
By far the easiest way to do that would be like this: 到目前为止,最简单的方法是这样的:
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);
Assigning values to properties is already built-in to C#, so instead of providing a restrictive API that can't possibly enable you to do everything you'd want to do, the AutoFixture philosophy is to use the language constructs already available . 为C#已经内置了为属性赋值的功能,因此AutoFixture的理念是使用已经可用的语言结构 ,而不是提供一个限制性API,使您无法完成所有想做的事情。
The next philosophical step is that if you often need to do something like that, the SUT could probably benefit from a redesign. 下一个哲学步骤是,如果你经常需要做那样的事情,那么SUT可能会从重新设计中受益。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.