简体   繁体   English

如何使用 AutoFixture 自定义 SpecimenBuilder 创建对象的新实例

[英]How to create new instances of objects with custom SpecimenBuilder with AutoFixture

Currently I have such code:目前我有这样的代码:

private ConnectedClient WithConnection(IConnection connection)
{
    var builder = new ClientWithConnectionSpecimenBuilder(connection);

    Fixture.Customizations.Add(builder);
    var client = Fixture.Create<ConnectedClient>();
    Fixture.Customizations.Remove(builder);

    return client;
}

Basically I need to create new instances of ConnectedClient class in my tests code with specified connection.基本上我需要在我的测试代码中使用指定的连接创建ConnectedClient class 的新实例。 And I've built custom specimen builder to do it.我已经建立了定制的标本生成器来做到这一点。

But there is no method like但是没有类似的方法

Fixture.Create<T>(specimenBuilder) 

so I need to customize the fixture.所以我需要定制夹具。

"Fixture" there is the inherited protected property of my base tests class that is already set up with some custom AutoMoqData customization so I need to reuse it for creating objects. “夹具”有我的基本测试 class 的继承保护属性,它已经设置了一些自定义 AutoMoqData 自定义,因此我需要重用它来创建对象。

It should be possible to use the one-off Build method to customize using a particular specimen builder:应该可以使用一次性Build方法使用特定的样本构建器进行自定义:

var client = fixture.Build<ConnectedClient>().FromFactory(builder).Create();

Note that doing this will disable any other customizations from the fixture.请注意,这样做将禁用灯具的任何其他自定义。

The DSL supports a bit more customization using With and Without , so if there's some additional customization you want to do on properties, you can do that: DSL 支持使用WithWithout进行更多的自定义,因此如果您想对属性进行一些额外的自定义,您可以这样做:

var client = fixture.Build<ConnectedClient>()
    .FromFactory(builder)
    .With(cc => cc.SomeProperty, () => fixture.Build<T>().FromFactory(otherFactory).Create())
    .Create();

But that will get pretty tedious for significant customization.但是对于重要的定制来说,这将变得相当乏味。 Autofixture is opinionated in this way. Autofixture 以这种方式自以为是。

The Build method is really intended as a one-off solution. Build方法实际上是一种一次性的解决方案。 If you want to rely more on the machinery of Autofixture to do everything except for creating the client connection, I would suggest relying on the existing Freeze method and Frozen attribute to keep the injected IConnection the same for a given ConnectedClient , which would obviate the need for a specific ISpecimenBuilder .如果您想更多地依赖 Autofixture 的机器来完成了创建客户端连接之外的所有操作,我建议您依靠现有的Freeze方法和Frozen属性来保持注入的IConnection对于给定的ConnectedClient相同,这将消除需要对于特定的ISpecimenBuilder

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM