How to assign a property only to a submenu of items in a list?

I want to create a list of custom objects using AutoFixture . I want the first N objects to have the property set to one value, and the rest to set it to another value (or just set according to the Fixture strategy by default).

I know that I can use Fixture.CreateMany<T>.With , but this will apply the function to all members of the list.

NBuilder has methods called TheFirst and TheNext (among others) that provide this functionality. An example of their use:

For the Foo class:

 class Foo { public string Bar {get; set;} public int Blub {get; set;} } 

You can create an instance of Foo like this:

 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 } } 

Here is a list of objects of type Foo with the following properties:

 [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 values Bar9 and Bar10 represent NBuilder 's default naming scheme)

Is there a β€œbuilt-in” way to achieve this with AutoFixture ? Or an idiomatic way to tune the device this way?

+6
source share
1 answer

The easiest way to do this would be as follows:

 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 into C #, so instead of providing a restrictive API that cannot allow you to do everything you want to do, AutoFixture's philosophy is to use existing language constructs .

The next philosophical step is that if you often need to do something, SUT is likely to benefit from a redesign.
+10
source

Source: https://habr.com/ru/post/955642/


All Articles