c# - AutoFixure Fixture.Build().With() 具有不同的值
问题描述
考虑一个类
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
所有值都相同。但我预计会看到这个属性的不同值。
我怎样才能达到它?
解决方案
该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())
);
在您的情况下,您选择静态的,它总是为指定的属性分配相同的值。
推荐阅读
- angular - NGRX 存储 - 服务器上的数据更改未应用于状态
- c# - 验证我收到的是否是整数
- reactjs - 赛普拉斯测试 - redux 商店是空的
- laravel - 从 Outlook 帐户获取电子邮件时出现“无消息”Imap Laravel 错误?
- c# - 在 Asp Net MVC 中排除来自 IdentityUser 的电子邮件
- javascript - 我对 react-modal 有一个奇怪的问题
- c# - 正则表达式替换为 C# 中的括号变量
- javascript - 在 html 页面加载之前运行 google 脚本
- java - 为什么 Maven 看不到 JavaFX 图形模块(而 Eclipse 有)
- mongodb - 如何使用工作副本机器同步 MongoDB 故障转移?