java方法调用堆栈调用时间_java - doNothing()方法正在调用实际方法 - 堆栈内存溢出...

我正在尝试在调用最终的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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值