我正在使用AutoFixture和AutoMoq来生成和配置Mock 到 interface。该接口使用MaxLength
属性来指定每个属性的最大长度。
如何使生成的模拟尊重该MaxLength
属性。
请考虑一下我有大量使用此属性的属性吗?(不仅仅是一个,就像在这个例子中一样)。
创建模拟的代码是这样的:
var fixture = new Fixture();
fixture.Customize(new AutoMoqCustomization() { ConfigureMembers = true });
var my = fixture.Create<IMyClass>();
MyClass 在哪里:
public interface IMyClass()
{
[MaxLength(40)]
public string Name { get; set; }
...
... more properties using the MaxLenght attribute
...
}
我尝试过像这样制作自定义样本生成器:
public class MaxLenghtSpecimenBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
var pi = request as PropertyInfo;
if (pi == null || pi.PropertyType != typeof(string))
{
return new NoSpecimen();
}
var maxLengthAttribute = (MaxLengthAttribute)Attribute.GetCustomAttribute(pi, typeof(DescriptionAttribute));
if (maxLengthAttribute != null)
{
return new ConstrainedStringGenerator().Create(new ConstrainedStringRequest(maxLengthAttribute.Length), context);
}
return new NoSpecimen();
}
}
为了通过调用将其添加到夹具中fixture.Customizations.Add(new MaxLenghtSpecimenBuilder());
但它不起作用。它没有获得自定义属性。它总是返回 null。