【问题标题】:Generate anonymous number for string property with AutoFixture使用 AutoFixture 为字符串属性生成匿名数字
【发布时间】:2012-02-09 10:22:45
【问题描述】:

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

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

这可能吗?

【问题讨论】:

    标签: c# unit-testing autofixture


    【解决方案1】:

    解决此问题的最佳方法是create a convention based custom value generator,它将匿名数值的字符串表示分配给特定属性,根据其名称

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

    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.Customizations 集合将它添加到您的 Fixture 实例中:

    var fixture = new Fixture();
    fixture.Customizations.Add(new StringThatReallyIsANumberGenerator());
    
    var anonymousFoo = fixture.CreateAnonymous<Foo>();
    

    【讨论】:

    • 谢谢,我稍微更新了类,所以构造函数将属性的名称作为参数。这样我也可以在其他地方使用该课程。
    • @Krimson 酷。我很高兴能帮上忙:)
    • 这在我需要为特定字符串属性而不是基于 GUID 的默认值生成有效 URL 的情况下也很有帮助。
    猜你喜欢
    • 2015-05-14
    • 2014-09-10
    • 2016-05-14
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多