简体   繁体   English

Mockito在存根时从超类调用真实方法

[英]Mockito calls real method from superclass when stubbing

I am getting problem with Mockito trying to call real method while stubbing. 我遇到了Mockito尝试在存根时调用真实方法的问题。 I assume this might be related to that method is inherited. 我认为这可能与继承该方法有关。 This is component external to my system and can't do really much about it. 这是我系统外部的组件,不能做太多事情。 But let's get to the code 但是让我们看一下代码

AbstractRpcClient abstractRpcClient = mock(AbstractRpcClient.class);
doNothing().when(abstractRpcClient).callOnce(anyString(), anyVararg());

Since callOnce calls methods on some other objects I get NPE right in the second line. 由于callOnce在其他一些对象上调用方法,因此我在第二行中获得了NPE。 AbstractRpcClient inherits from another abstract class, but this class is package local, so I can't even cast it in my stubbing. AbstractRpcClient继承自另一个抽象类,但是该类是本地程序包,因此我什至无法将其强制转换为存根。

Is there anything I can do about it? 有什么我可以做的吗? How can I stub this method to do nothing or throw exception WITHOUT calling real method. 我如何才能在不调用真实方法的情况下使该方法不执行任何操作或引发异常。

Do I have to extend this class in test and override method callOnce ? 我必须在测试中扩展此类并重写方法callOnce吗? This of course works, but is there any other solution? 当然可以,但是还有其他解决方案吗?

Minimal example: 最小示例:

package external.component;

public abstract class ClassToMock extends SuperClass {

}


abstract class SuperClass {
    public void callOnce(String method, Object... params) {
        throw new RuntimeException("We shouldn't be here");
    }
}

Test class 测试班

package mypackage

import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.anyVararg;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;

public class Testclass {

    @Test
    public void test() {
        external.component.ClassToMock classToMock = mock(external.component.ClassToMock.class);
        doNothing().when(classToMock).callOnce(anyString(), anyVararg());
    }

}

In example of course RuntimeException is thrown from callOnce method. 当然,在示例中, callOnce方法抛出RuntimeException

It looks like bug in Mockito and actually it was already reported and was supposed to be fixed over a year ago: 它看起来像Mockito中的错误,实际上已经被报告,并且应该在一年前就已修复:

https://github.com/mockito/mockito/issues/168 https://github.com/mockito/mockito/issues/168

I am getting the same (broken) behaviour in versions 1.9.5 and most recent 1.10.19. 我在1.9.5版和最新的1.10.19版中得到了相同的(中断)行为。

I would recommend that you raise the bug with Mockito. 我建议您使用Mockito引发该错误。

As a temporary work-around there are a few options: 作为临时解决方法,有几种选择:

  • make the class public 公开课
  • add public void callOnce() { super.callOnce(); } 添加public void callOnce() { super.callOnce(); } public void callOnce() { super.callOnce(); } in the child class public void callOnce() { super.callOnce(); }在子类中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM