【问题标题】:Autofixture - base property in new list on property from a previously constructed oneAutofixture - 新列表中的基础属性来自先前构建的属性
【发布时间】:2019-03-07 23:47:04
【问题描述】:

我想我遗漏了一些东西,但我想做的是:

我的 C# 代码中有两个数据库实体。一个是另一个的孩子,因此孩子包含一个应该引用父母 ID 的字段。

父类如下

public class Product
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public decimal Price { get; set; }

    public decimal DeliveryPrice { get; set; }
}

子类如下:

public class ProductOption
{
    public Guid Id { get; set; }

    public Guid ProductId { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }
}

我已经创建了一个随机“父母”列表:

var products = fixture.CreateMany<Product>(5).ToList();

然后我想做的是创建 10 个子对象,并从 AutoFixture 创建的产品列表中随机给它们一个ProductId。所以我尝试了这个:

var rand = new Random();
var options = fixture.Build<ProductOption>()
    .With(option => option.ProductId, products[rand.Next(0, 5)].Id)
    .CreateMany(10)
    .ToList();

几乎起作用了,但我发现所有的ProductIds 都是同一个,所以它显然只命中了一次rand.Next

我正在做的事情是否可行/可取?

【问题讨论】:

    标签: c# .net unit-testing testing autofixture


    【解决方案1】:

    当我为该属性提供价值时,我希望使用相同的构建器/固定装置构建的所有实例都将提供价值。
    所以你注意到的是期望的行为。

    您可以提供一个“工厂”,而不是已经生成的值,它将在实例创建期间为属性生成值。
    最新的 Autofixture 版本为接受函数作为参数的 .With 方法引入了重载。

    var rand = new Random();
    Func<Guid> pickProductId = () => products[rand.Next(0, 5)].Id;
    
    var options = 
        fixture.Build<ProductOption>()
               .With(option => option.ProductId, pickProductId)
               .CreateMany(10)
               .ToList();
    
    // Prove
    options.Select(o => o.ProductId).ToHashSet().Should().HaveCountGreaterThan(1); // Pass Ok
    

    【讨论】:

    • 啊,是的,我正在查看智能感知过载,但我有点困惑。这实际上很有意义,一个充当“生成器”的函数谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    相关资源
    最近更新 更多