[英]How do you mock a method which uses a private static inner class as a parameter?
我有一个带有采用单个参数的方法的类。 此参数是模拟类内部的嵌套类,但它是私有的(而且是静态的,但我认为这没有太大区别)。 我该如何模拟这种方法?
例:
public class myClass {
public anotherObject;
public myClass(AnotherObject anotherObject) {
this.anotherObject = anotherObject;
}
public void exec() {
//Some instructions ...
//This second method is inside another completely seperate class.
anotherObject.secondMethod(new NestedClass());
}
private static class NestedClass {
public NestedClass() {
//Constructor
}
//Variables and methods, you get the picture
}
}
在上面的示例中,secondMethod(...)是我要模拟的方法。
寻找该问题的其他示例的所有尝试都只是返回与模拟单个私有嵌套类或模拟静态类有关的结果,这些结果与此并不完全相关,并且似乎并没有提供我可以发现的解决方案。
编辑:我正在寻找某种看起来像这样的解决方案:
@Test
public void testExec() {
AnotherObject anotherObject = mock(AnotherObject.class);
when(anotherObject.secondMethod(any(NestedClass.class))).thenReturn(0);
MyClass testThisClass = new MyClass(anotherObject);
}
注意:不允许修改我担心的代码,仅允许创建这些测试,以确保当前的实现在进行修改时可以在以后进行。
如果我正确理解了需求,请添加一种方法,称为executeSecondMethod()。 在您的主方法类中调用此方法。
public class myClass {
public void exec() {
//Some instructions ...
secondMethod(new NestedClass());
}
public void secondMethod(NestedClass example) {
//Some instructions that I want to just mock out...
}
private static class NestedClass {
//Variables and methods, you get the picture
}
public static executeSecondMethod(){
secondMethod(new NestedClass()); // pass the nested class object here
}
}
public class mainClass{
public static void main(){
executeSecondMethod();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.