gpt4 book ai didi

unit-testing - 如何将 Autofixture (v3) 与 ICustomization、ISpecimenBuilder 一起使用来处理构造函数参数?

转载 作者:行者123 更新时间:2023-12-04 02:02:29 25 4
gpt4 key购买 nike

我正在尝试克服一个场景,其中一个类具有一个字符串构造函数参数,该参数不能被 Autofixture 生成的任何旧字符串(Guid-y 外观值)所满足。

在您想简单地通过 Mark Seemann's Ploeh blog entry on Convention-based Customizations 的链接来回答之前,让我说我一直在引用它和他的其他博客条目来进行这个测试,但我无法通过。

当我单步调试时,我可以看到在某些时候构造函数参数传入了有效值,但测试仍然失败,并显示 Guid-y 颜色值。我认为这与 Autofixture 填充“颜色”参数值和“颜色”属性有关。是不是我编写了一个解决构造函数参数的 ISpecimenBuilder,但我正在测试公共(public)属性值(两个不同的东西)?

我知道所有这些对于示例来说都是多余的,但我设想了一个更复杂的场景,其中使用 Build<T>().With()方法不会是 DRY。

失败的测试

    [Fact]
public void Leaf_Color_Is_Brown()
{
// arrange
var fixture = new Fixture().Customize(new LeafColorCustomization());

// act
var leaf = fixture.Create<Leaf>();

// using .Build<>.With(), test passes
//var leaf = fixture.Build<Leaf>().With(l => l.Color, "brown").CreateAnonymous();

// assert
Assert.True(leaf.Color == "brown");
}

SUT

    public class Leaf
{
public Leaf(string color)
{
if (color != "brown")
throw new ArgumentException(@"NO LEAF FOR YOU!");

this.Color = color;
}
public string Color { get; set; }
}

CompositeCustomization 实现 (我知道在这个例子中不需要 AutoMoqCustomization())

    public class LeafCustomization : CompositeCustomization
{
public LeafCustomization()
: base(
new LeafColorCustomization(),
new AutoMoqCustomization()) { }
}

Leaf-specific ICustomization

    public class LeafColorCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
if (fixture == null)
throw new ArgumentNullException("fixture");

fixture.Customizations.Add(new LeafBuilder());
}
}

特定颜色的字符串构造函数 ISpecimenBuilder

    public class LeafBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
var pi = request as ParameterInfo;
if (pi == null)
return new NoSpecimen(request);

if (pi.ParameterType != typeof(string) || pi.Name != "color")
return new NoSpecimen(request);

return "brown";
}
}

最佳答案

解决方案一 :

注册 Color作为后处理的一部分,不应为可写属性分配任何自动值:

internal class LeafColorCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<Leaf>(c => c
.Without(x => x.Color));

fixture.Customizations.Add(new LeafBuilder());
}
}

解决方案二 :

制作 Color属性只读:

public class Leaf
{
private readonly string color;

public Leaf(string color)
{
if (color != "brown")
throw new ArgumentException(@"NO LEAF FOR YOU!");

this.color = color;
}

public string Color
{
get { return this.color; }
}
}

由于 Color属性是只读的 AutoFixture 不会为其分配值。

The above solutions apply also to AutoFixture 2.

关于unit-testing - 如何将 Autofixture (v3) 与 ICustomization、ISpecimenBuilder 一起使用来处理构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15531321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com