Consider a class
class A
{
public class NestedA
{
public string StrWithInt { get; set; }
public string Str1 { get; set; }
public string Str2 { get; set; }
}
public List<NestedA> Items { get; set; }
}
I am using AutoFixture framework for generating instances of class A
with random contents.
The NestedA
's class property StrWithInt
is a string
type but its value has to be a number, int value. So I am using a With() method to customize generation.
My code looks like below:
Random r = new Random();
Fixture fixture = new Fixture();
fixture.Customize<A.NestedA>(ob =>
ob.With(p => p.StrWithInt, r.Next().ToString())
);
var sut = fixture.Build<A>().Create();
foreach (var it in sut.Items)
{
Console.WriteLine($"StrWithInt: {it.StrWithInt}");
}
Console.ReadLine();
I get a such result.
StrWithInt: 340189285
StrWithInt: 340189285
StrWithInt: 340189285
All values are same. But I am expected to see different values of this property.
How Can I reach it?
The With(...)
method has many overloads among which you can find the following:
IPostprocessComposer<T> With<TProperty>(
Expression<Func<T, TProperty>> propertyPicker,
Func<TProperty> valueFactory);
So you can use this one via passing factory of random numbers and after this result always will be different:
fixture.Customize<A.NestedA>(ob =>
ob.With(p => p.StrWithInt, () => r.Next().ToString())
);
In your case you choose the static one which always assign the same value to the specified property.