我使用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; }
添加到抽象类Bar
,那么一切都很好。我真的认为这是次优解决方案,因为我不想公开属性age
。它只是用来计算其他东西。
如何在不为了测试而暴露属性的情况下解决此问题。是否有另一个库可以在没有这个问题的情况下达到同样的效果?
答案 0 :(得分:1)
当获取目标类的属性并与源类型的构造函数匹配时出现问题时会引发此错误,尽管错误读取时只是映射了构造函数。
在您的情况下,内部异常是由于两个类中都没有公共属性。我很确定你的修复只是将映射重定向到你的虚拟属性。
您可以在基类上使用public int age { get { return _age; } }
进行修复 - 在此示例中几乎没有什么危害。
此类问题的常见逃逸方法是使用InternalVisibleTo
,但在映射类型时,libary当前仅使用BindingFlags.Public
,因此它不会看到为此目的创建的内部属性。
除了BindingFlags.NonPublic
之外,我还可以通过调整the source来使用BindingFlags.Public
来创建代理,但我不确定这是一种合理的做法。