【问题标题】:Faking derived class but calling the real constructor and ignoring base constructor伪造派生类但调用真正的构造函数并忽略基构造函数
【发布时间】:2017-08-27 09:21:22
【问题描述】:

我有以下课程:

public class Base
{
    private int x;
    public Base(int _x) { x = _x; }
}
public class Derived : Base
{
    int y;
    public Derived(int _x,int _y) : base(_x) { y = _y; }
}

我想创建一个假的“派生”对象,但要调用原始构造函数并忽略基本构造函数。 我该怎么做?

【问题讨论】:

  • 伪造派生类是什么意思?你想做什么?
  • 你不能。派生类总是需要显式调用基类构造函数,如您的情况,或者如果基类具有默认构造函数,则隐式调用。
  • 退后一步,向我们解释您真正的潜在业务问题。你认为你为什么需要这个?
  • 我有一个无法更改的基类。我想伪造“派生”对象方法,但调用构造函数的原始实现,并忽略对基本构造函数的调用。

标签: c# unit-testing mocking


【解决方案1】:

其实我找到了解决办法。 我调查了一下,发现我可以用Typemock做到这一点:

Isolate.Fake.Instance<Derived(Members.CallOriginal,ConstructorWillBe.Called, BaseConstructorWillBe.Ignored);

它允许我创建一个假对象,调用原始构造函数并忽略基本构造函数。

【讨论】:

    【解决方案2】:

    你不能。在实例化Derived 对象时,Base 的构造函数必须运行;毕竟Derived实例也是Base,创建Base的逻辑必须在进程的某处执行。

    您可能会混淆不调用base 构造函数与为您隐式调用它的情况;当Base 有一个可访问的默认构造函数时会发生这种情况:

    public class Base
    {
        private int x;
        public Base() { } //default constructor
        public Base(int _x) { x = _x; }
    } 
    

    那么这是合法的:

    public class Derived : Base
    {
        int y;
        public Derived(int _y) { y = _y; } //no explicit base() needed.
    }
    

    但这只是因为编译器会为您添加隐式调用。真正的代码是:

    public class Derived : Base
    {
        int y;
        public Derived(int _y) : base() { y = _y; }
    }
    

    这似乎是XY Problem。你真正想做什么?

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 2016-07-19
      • 2018-07-16
      • 2014-11-17
      • 2015-08-18
      • 2022-12-03
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多