首页 > 解决方案 > 生成子列表

问题描述

我有以下两个课程:

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 个帖子。

标签: c#.netintegration-testingxunitautofixture

解决方案


但是帖子的集合是空的。

不完全的; Posts集合是的,因为它们在Blog构造函数中被初始化为空 HashSets。

我如何使用 Autofixture 生成博客和相应的帖子

fixture.AddManyToDo块中使用:

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 个对象。


推荐阅读