Java 使用 Mockito 在与被测类 (CUT) 相同的类中存根方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20974892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Mockito to Stub methods in the same class as the class under test (CUT)
提问by Sudhir
I am trying to test some legacy code using Mockito, and the method is a of type void.
我正在尝试使用 Mockito 测试一些遗留代码,该方法是 void 类型。
I have stubbed out a lot of the calls to methods in other classes, this works fine. However, I also need to be able to stub out certain calls to other methods inside the same class.
我已经删除了很多对其他类中方法的调用,这很好用。但是,我还需要能够排除对同一类中其他方法的某些调用。
Currently this is not working.
目前这不起作用。
e.g. My Class is like below:
例如我的班级如下:
public class Test {
public Test(dummy dummy) {
}
public void checkTask(Task task, List <String> dependencyOnLastSuccessList) throws TaskException {
callToOtherClass.method1 // This works fine, I can stub it using mockito
updateAndReschedule(Long id, String message) // call to method in same class, I cannot stub it
}
public void updateAndReschedule(Long id, String message) {
//method logic.....
}
}
This is my testClass showing what I have at the minute:
这是我的 testClass 显示了我现在所拥有的:
@Test
public void testMyMethod() {
Test testRef = new Test(taskJob);
Test spy = spy (testRef);
// when a particular method is called, return a specific object
when(callToOtherClass.method1).thenReturn(ObjectABC);
//doNothing when my local method is called
doNothing().when(spy).updateAndReschedule(1, "test");
//make method call
spy.checkTask(ts, taskDependencies);
}
采纳答案by fatih
You should instantiante testRef as follows:
您应该按如下方式实例化 testRef:
Test testRef = new Test(taskJob) {
public void updateAndReschedule(Long id, String message) {
//do nothing
}
};
No need for the spy.
不需要间谍。
回答by marek.kapowicki
In my opinion the spy object instead of mock. Spy is a mock created as a proxy to an existing real object; some methods can be stubbed, while the unstubbed ones are forwarded to the covered object
在我看来,间谍对象而不是模拟对象。Spy 是一个模拟,作为现有真实对象的代理;一些方法可以被存根,而未被存根的被转发到被覆盖的对象
The spy is more elegant than anonymous implementation of chosen methods
间谍比所选方法的匿名实现更优雅
Look at the example:
看例子:
Mockito: Trying to spy on method is calling the original method
the nice article about mockito You can read
关于mockito的好文章你可以阅读