【问题标题】:Generate child list生成子列表
【发布时间】:2019-01-22 06:44:08
【问题描述】:

我有以下两个类:

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 属性有私有设置器。 AutoFixture 没有内置支持将值分配给非公共字段或属性。这是设计使然。

标签: c# .net integration-testing xunit autofixture


【解决方案1】:

但帖子的收藏为空。

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

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

Do 块中使用fixture.AddManyTo

var fixture = new Fixture();
var blogs = fixture.Build<Blog>()
    .Without(b => b.BlogId)
    .Do(b => fixture.AddManyTo(b.Posts, 10))
    .CreateMany(10);

这将创建 10 个 Blog 对象,每个对象在 Posts 集合中都有 10 个 Post 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-18
    • 2023-01-31
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多