9

我正在尝试创建一个自定义项,允许我指定不应填充不在某个命名空间中的类型的属性。

基本上,我试图改变这一点:

fixture.Customize<Window>(c => c.OmitAutoProperties());
fixture.Customize<ContentControl>(c => c.OmitAutoProperties());
fixture.Customize<TextBlock>(c => c.OmitAutoProperties());
// Many many more...

对此:

fixture.Customize(t => !t.Namespace.StartsWith("MyProject"),
                  c => c.OmitAutoProperties());

如何做到这一点?

实际上,我只关心结果,而不关心此处显示的虚构 API,因此实现我自己的 APIISpecimenBuilderICustomization不是问题。

4

1 回答 1

4

最简单的方法可能是通过自定义样本生成器

public class OmitPropertyForTypeInNamespace : ISpecimenBuilder
{
    private readonly string ns;

    public OmitPropertyForTypeInNamespace(string ns)
    {
        this.ns = ns;
    }

    public object Create(object request, ISpecimenContext context)
    {
        if (IsProperty(request) &&
            IsDeclaringTypeInNamespace((PropertyInfo)request))
        {
            return new OmitSpecimen();
        }

        return new NoSpecimen(request);
    }

    private bool IsProperty(object request)
    {
        return request is PropertyInfo;
    }

    private bool IsDeclaringTypeInNamespace(PropertyInfo property)
    {
        var declaringType = property.DeclaringType;
        return declaringType.Namespace.Equals(
            this.ns,
            StringComparison.OrdinalIgnoreCase);
    }
}

像往常一样,提供匹配的自定义也是一个很好的约定:

public class OmitAutoPropertiesForTypesInNamespace : ICustomization
{
    private readonly string ns;

    public OmitAutoPropertiesForTypesInNamespace(string ns)
    {
        this.ns = ns;
    }

    public void Customize(IFixture fixture)
    {
        fixture.Customizations.Add(new OmitPropertyForTypeInNamespace(this.ns));
    } 
}

这最终会让你说:

var fixture = new Fixture();
fixture.Customize(new OmitAutoPropertiesForTypesInNamespace("MyProject"));
于 2013-06-25T15:47:17.460 回答