考虑上课
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; }
}
我正在使用AutoFixture框架生成具有随机内容的类A
的实例。
NestedA
的类属性StrWithInt
是string
类型,但其值必须是数字,即int值。因此,我正在使用With()方法来自定义生成。
我的代码如下:
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();
我得到这样的结果。
StrWithInt:340189285
StrWithInt:340189285
StrWithInt:340189285
所有值均相同。但是,我希望看到该属性的其他值。
如何到达?
答案 0 :(得分:0)
With(...)
方法有很多重载,您可以在其中找到以下内容:
IPostprocessComposer<T> With<TProperty>(
Expression<Func<T, TProperty>> propertyPicker,
Func<TProperty> valueFactory);
因此,您可以通过传递随机数的工厂来使用此地址,此结果总是会有所不同:
fixture.Customize<A.NestedA>(ob =>
ob.With(p => p.StrWithInt, () => r.Next().ToString())
);
在这种情况下,请选择始终为指定属性分配相同值的静态变量。