2012-02-09 56 views
4

我正在测试一些映射方法的单元,并且我有一个类型为string的source属性,它被映射到integer类型的destination属性。使用AutoFixture为字符串属性生成匿名数

所以我想让AutoFixture为特定的字符串属性创建一个匿名整数的源对象,而不是所有的字符串属性。

这可能吗?

回答

6

解决这将是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>(); 
+0

感谢名单,我更新了类很少,所以该构造函数将名字的财产作为参数。因此我也可以在其他地方使用课程。 – Krimson 2012-02-09 10:57:23

+0

@Krimson酷。我很高兴我可以帮助:) – 2012-02-09 11:00:28

+1

这在我需要为特定字符串属性(而不是基于GUID的默认值)生成有效URL的情况下也很有帮助。 – 2015-02-11 14:36:09