我正在尝试在调用最终的void方法时执行doNothing(),但doNothing()调用却在调用实际方法。
SwitchWorker类
public class SwitchWorker {
public boolean switchMethod(String id){
this.methodA(id);
return true;
}
public void methodA(String id){
final Switch switchObj = Switch.getSwitchInstance();
switchObj.finalVoidMethod(id);
// XYZ......
}
}
开关类别
public final class Switch {
private static final Switch INSTANCE = new Switch();
private Switch() { //Private Constructor
super();
}
public static Switch getSwitchInstance() {
return INSTANCE;
}
public final synchronized void finalVoidMethod(String param) {
// Do Something
}
}
测试代码:
@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("com.application.switching.Switch")
public class SwitchWorkerTest {
@Test
public void test() throws Exception {
SwitchWorker swObj = new SwitchWorker();
final String channelId = "0001";
Switch switchMock = mock(Switch.class);
PowerMockito.mockStatic(Switch.class);
when(Switch.getSwitchInstance()).thenReturn(switchMock);
doNothing().when(switchMock).finalVoidMethod(channelId);
boolean result = swObj.switchMethod(channelId);
assertTrue(result);
}
我是否缺少doNothing()方法的任何内容?
"doNothing().when(switchMock).finalVoidMethod(channelId);"
doNothing()正在调用实际的finalVoidMethod()而不是模拟。 但是,switchMock是模拟对象。
我已经查看了关于PowerMockito,模拟静态方法和doNothing方法的几乎所有关于堆栈溢出的问题,我不确定是否遗漏了什么,因为我遵循了大多数示例来构建代码。 我也添加了@PrepareForTest,但后来将其删除了。
谢谢。
编辑:我剪断代码,使其更抽象,并稍作更改以适合@kswaughs评论
public boolean mockedMethod(final String input) {
System.out.println("0----------------------");
final Switch switchObj = Switch.getSwitchInstance();
System.out.println("1:switchObj: "+ switchObj);
switches.refresh("input");
System.out.println("2----------------------");
return true;
}
带有测试代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Switch.class, SwitchWorker.class})
public class SwitchWorkerTest {
@Test
public void test() throws Exception {
SwitchWorker swObj = new SwitchWorker();
Switch switchMock = mock(Switch.class);
PowerMockito.mockStatic(Switch.class);
when(Switch.getSwitchInstance()).thenReturn(switchMock);
boolean result = swObj.mockedMethod("0001");
assertTrue(result);
返回。
0----------------------
1:switchObj: Mock for Switch, hashCode: 1659309731
java.lang.NullPointerException
at com.application.switching.Switch.refresh(Switch.java:238)
at com.application.switching.SwitchWorker$1.run(SwitchWorker.java:51)