I'm trying to create a list of objects that have some variance in their data. Types such as strings etc are fine as they are random each time, however I've found that bool's are always the same value in each object within a collection generated by CreateMany().
Example class, for demonstration sake:
public class FooBar
{
public string Name { get; set; }
public bool IsFoo { get; set; }
public bool IsBar { get; set; }
}
var fooBars = new Fixture().Build<FooBar>().CreateMany(5).ToList();
// Result
fooBars[0].IsFoo; // true
fooBars[1].IsFoo; // true
fooBars[2].IsFoo; // true
...
Can the below be achieved?
// Wanted result
fooBars[0].IsFoo; // true
fooBars[1].IsFoo; // false
fooBars[2].IsFoo; // true
fooBars[3].IsFoo; // false
...
Cheers!
AutoFixture does give you alternating booleans, but what you're experiencing here is a resonance effect, because you also have the IsBar property; for each instance of FooBar created, AutoFixture will alternate between true and false, and thus always set IsFoo to true, and IsBar to false.
Deterministic alternation probably isn't the best fit for this scenario. It probably would be better to randomise boolean values. One way to do that would be something like this:
var r = new Random();
fixture.Register<bool>(() => r.NextDouble() < 0.5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With