c# - 如何使用 AutoFixture 为属于类的属性生成数据?

标签 c# .net autofixture

我正在尝试自定义在类中生成的数据..其中属性是另一个类。

例如。

public class Foo
{
   public string Id { get; set; }
   public Baa Baa { get; set; }
}


public class Baa
{
   // 30 properties which are strings, ints, etc.
}

我想知道我是否可以做这样的事情......

var fixture = new Fixture();
return fixture.Build<Foo>()
    .With(x => x.Id, $"Foo-{fixture.Create<int>()}")
    .With(x => x.Baa, CreateSomeCustomBaaUsingAutofixture)
    .Create();

然后..

private Baa CreateSomeCustomBaaUsingAutofixture()
{
    var fixture = new Fixture();
    return fixture.Build<Baa>()
        .With(lots of customizations here)
    .Create();
}

有没有更干净的方法来做到这一点?或者..这基本上是唯一/推荐的方法?

我知道 AutoFixture 可以自动为我创建一个 Baa 实例以及其中的属性数据。我只是希望对其进行更多自定义。

最佳答案

由于您想按照约定配置Baa,因此您可以简单地这样做。它可能看起来像这样:

fixture.Customize<Baa>(c => c
    .With(x => x.Baz, "Corge")
    .With(x => x.Qux, "Garply"));

每当您创建 Foo 对象时,Baa 属性都会根据这些规则创建一个值:

var foo = fixture.Create<Foo>();
Console.WriteLine(foo.Baa.Baz);
Console.WriteLine(foo.Baa.Qux);

打印:

Corge
Garply

关于c# - 如何使用 AutoFixture 为属于类的属性生成数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215764/

相关文章:

c# - 自动夹具 + AutoMoq : Create mock with excluded property

c# - 如何保持单元测试干燥并减少断言

c# - 通过描述获取枚举值

c# - 在代码隐藏中数据绑定(bind)到 objective-c LR 属性

c# - 我可以在 ConcurrentBag 上使用普通的 foreach 吗?

c# - 强制执行 JIT

c# - 防止将 "superflous"文件复制到我的 Release 目录中

c# - 在 MySQL 中使用子类型时遇到问题

c# - 不同域/项目中的相同界面

c# - 具有多个相同类型实例的构造函数