我想使用Powermock(基于EasyMock)模拟私有静态内部类。这不是来自生产代码,这只是一个问题是否可行。我可以肯定这是一个不好的设计,但这是我为科学所做的尝试。
假设我们有一个带有静态私有内部类的类:
public class Final {
private static class Inner {
private final int method () { return 5; }
}
public int callInnerClassMethod () {
return new Inner().method();
}
}
我想模拟Inner
类及其method
。
我的代码如下:
Class<?> innerType = Whitebox.getInnerClassType(Final.class, "Inner");
Object innerTypeMock = PowerMock.createMock(innerType);
PowerMock.expectNew(innerType).andReturn(innerType);
PowerMock.expectPrivate(innerType, "method").andReturn(42);
PowerMock.replay(innerTypeMock);
new Final().callInnerClassMethod();
在代码中:我们得到Inner.class
的类型并对其进行模拟,当用户创建类型为Inner
的新对象时,我们说我们返回实例,而当有人调用它的{{1 }}我们为此提供了实现。
通常,我正在学习有关模拟的知识,可以肯定的是,这段代码证明了我不知道自己在做什么。该代码甚至无法编译,并且在行method
上出现以下错误:
和IExpectationSetters中的return(捕获)不能应用于 (java.lang.Object)
甚至可以模拟私有静态内部类吗?我尚未在SO上找到确定的代码示例。
答案 0 :(得分:0)
通过在代码中使用裸Class innerType = ...
而不是Class<?> innerType = ...
,我设法解决了编译错误。感觉不对,但是行得通。如果有人在原始示例中解释了差异以及如何使差异生效,我将不胜感激。在某些地方,我混合了innerType
和innerTypeMock
。完整的有效测试代码如下所示:
Class innerType = Whitebox.getInnerClassType(Final.class, "Inner");
Object innerTypeMock = PowerMock.createMock(innerType);
PowerMock.expectNew(innerType).andReturn(innerTypeMock);
PowerMock.expectPrivate(innerTypeMock, "method").andReturn(42);
PowerMock.replayAll();
System.out.println(""+new Final().callInnerClassMethod());