c# - 生成子列表
问题描述
我有以下两个课程:
public class Blog
{
public Blog()
{
Posts = new HashSet<Post>();
}
public int BlogId { get; set; }
public string Name { get; set; }
public ICollection<Post> Posts { get; private set; }
}
public class Post
{
public int PostId { get; set; }
public int BlogId { get; set; }
public string Uri { get; set; }
public Blog Blog { get; set; }
}
我尝试使用 AutoFixture 生成我想在测试中使用的示例数据。
var blogs = new List<Blog>(new Fixture().Build<Blog>()
.Without(x => x.BlogId)
.CreateMany(10));
但是帖子的集合是空的。
问题是我如何使用 Autofixture 生成博客和相应的帖子,假设每 10 个博客有 10 个帖子。
解决方案
但是帖子的集合是空的。
不完全的; Posts
集合是空的,因为它们在Blog
构造函数中被初始化为空 HashSets。
我如何使用 Autofixture 生成博客和相应的帖子
fixture.AddManyTo
在Do
块中使用:
var fixture = new Fixture();
var blogs = fixture.Build<Blog>()
.Without(b => b.BlogId)
.Do(b => fixture.AddManyTo(b.Posts, 10))
.CreateMany(10);
这将创建 10 个Blog
对象,每个Post
对象在Posts
集合中都有 10 个对象。
推荐阅读
- django - 计算休假天数并在 django admin 模型中显示
- database - 除了 informatica 之外,是否有将数据从 Snowflake 流式传输到 Oracle 的方法
- javascript - 用 * 替换字符串中的字符,但只有字符而不是空格 JavaScript 正则表达式
- asp.net-mvc - ASP.Net MVC - 运行后台进程/异步而不在前台等待
- windows - 查找 Rscript 批处理的绝对路径
- java - Java泛型通配符用于不同子类型的说明
- reactjs - ESlint、React、Typescript 在明确使用时提供 no-unused-vars
- r - 绘制两个不连续范围的所有排列
- tensorflow - TensorFlow Keras(v2.2) 模型适合多个输出和损失失败
- python - 在 Pycharm 中私下处理 pypi 发布包的最佳方式是什么?