2

我正在使用 Ploeh 的 SemanticComparison 库取得了巨大的成功——除非我有一个涉及的抽象类不公开其所有构造函数参数。

这是我得到的例外 -

Ploeh.SemanticComparison.ProxyCreationException : The proxy of Foo could not be created using the same semantic heuristics as the default semantic comparison. In order to create proxies of types with non-parameterless constructor the values from the source constructor must be compatible to the parameters of the destination constructor.
  ----> System.InvalidOperationException : Operation is not valid due to the current state of the object.

这是我能想到的最简单的例子 -

// this fails with the aforementioned exception
_fixture.Create<Foo>().AsSource().OfLikeness<Foo>().CreateProxy();

public class Foo : Bar
{
    public Foo(int age)
        : base(age)
    {           
    }
}

public abstract class Bar
{
    private readonly int _age;

    protected Bar(int age)
    {
        _age = age;
    }
}

但是,如果我添加public int NotAge { get; set; }到 abstract class Bar,那么一切都很好。我真的认为这是一个次优的解决方案,因为我不想公开 property age。它只是用来计算其他东西。

我怎样才能解决这个问题而不只是为了测试而暴露属性。是否有另一个库可以在没有这个问题的情况下达到相同的效果?

4

1 回答 1

1

当获取目标类的属性并与源类型的构造函数匹配时出现问题时会引发此错误,尽管错误读起来好像只有构造函数被映射。

在您的情况下,内部异常是由于两个类中都没有公共属性。我很确定您的修复只是将映射重定向到您的虚拟属性。

你可以在基类上修复它public int age { get { return _age; } }——在这个例子中几乎没有什么害处。

此类问题的通常逃生舱口是使用InternalVisibleTo,但库当前仅BindingFlags.Public在映射类型时使用,因此它不会看到为此目的创建的内部属性。

我可以通过调整要使用的源来创建代理,BindingFlags.NonPublicBindingFlags.Public我不确定这是一种合理的方法。

于 2015-05-21T13:34:22.077 回答