4

我正在对一些映射方法进行单元测试,并且我有一个字符串类型的源属性,它映射到整数类型的目标属性。

所以我希望 AutoFixture 使用匿名整数为特定字符串属性创建源对象,而不是为所有字符串属性。

这可能吗?

4

1 回答 1

8

解决这个问题的最佳方法是创建一个基于约定的自定义值生成器,它根据名称将匿名数值的字符串表示形式分配给特定属性。

所以,举个例子,假设你有一个这样的类:

public class Foo
{
    public string StringThatReallyIsANumber { get; set; }
}

自定义值生成器如下所示:

public class StringThatReallyIsANumberGenerator : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var targetProperty = request as PropertyInfo;

        if (targetProperty == null)
        {
            return new NoSpecimen(request);
        }

        if (targetProperty.Name != "StringThatReallyIsANumber")
        {
            return new NoSpecimen(request);
        }

        var value = context.CreateAnonymous<int>();

        return value.ToString();
    }
}

这里的关键点是自定义生成器将只针对名为的属性StringThatReallyIsANumber,在本例中这是我们的约定

为了在您的测试中使用它,您只需通过集合将它添加到您的Fixture实例中:Fixture.Customizations

var fixture = new Fixture();
fixture.Customizations.Add(new StringThatReallyIsANumberGenerator());

var anonymousFoo = fixture.CreateAnonymous<Foo>();
于 2012-02-09T10:28:58.357 回答