我在其中一个方法中有一个带有局部内部类的类:
public class Outer {
String hello = "hello";
public void myMethod() {
class Inner {
public void myInnerMethod() {
System.out.println(hello);
}
}
[...really slow routine...]
(new Inner()).myInnerMethod();
}
}
我想测试 myInnerMethod()
。因此,我使用反射实例化本地内部类,并对其调用 myInnerMethod()
。
public void test() {
Object inner = Class.forName("Outer$Inner").newInstance();
inner.getClass().getDeclaredMethod("myInnerMethod").invoke(inner); // hello will be null
}
但是当 myInnerMethod()
访问 hello
时,它在 Outer 类的范围内,它是 null
。
有没有办法模拟或以其他方式向 myInnerMethod()
提供 hello?
我知道我可以通过提取内部类或只测试 Outer 的公共(public)方法来重构我的代码。但是还有办法吗?
最佳答案
在能够验证内部行为之前,您需要进行一些小的重构:
1) 创建一个包含从 myInnerMEthod
中调用的代码的包级方法:
public class Outer {
String hello = "hello";
public void myMethod() {
class Inner {
public void myInnerMethod() {
Outer.this.printHello(hello); // !!! change here
}
}
[...really slow routine...]
(new Inner()).myInnerMethod();
}
void printHello(String hello){/* */} // !! add this
}
2) 监视 Outer
类并验证 printHello
是否已使用 hello 实例变量调用:
public void test() {
// Arrange
Outer outerSpy = spy(new Outer());
doNothing().when(outerSpy).printHello(anyString()); // optional
// Act
outer.myMethod();
// Assert
verify(outerSpy).printHello("hello");
}
关于java - 从本地内部类模拟访问外部对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55628238/