【问题标题】:Why can't I create a likeness proxy when abstract class not exposing every constructor argument?当抽象类不公开每个构造函数参数时,为什么我不能创建相似代理?
【发布时间】:2015-05-15 14:41:38
【问题描述】:

我在使用 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。它只是用来计算其他东西。

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

【问题讨论】:

    标签: c# unit-testing semantic-comparison


    【解决方案1】:

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

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

    您可以在基类上使用public int age { get { return _age; } } 修复它 - 在这个示例中几乎没有什么危害。

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

    我能够通过调整 the source 以使用 BindingFlags.NonPublicBindingFlags.Public 来创建代理,但我不确定这是一种合理的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 2018-02-27
      相关资源
      最近更新 更多