java mocked_java – 使用PowerMock的Mocked私有方法,但是底层方法仍然被调用

我试图嘲笑嘲弄一个正在进行JNDI呼叫的私有方法。当从单元测试中调用该方法时,会抛出异常^。我想嘲笑这种方法进行测试。我使用了

sample code from another questions answer,而测试通过,似乎底层方法仍然被调用。我在doTheGamble()方法中插入了一个System.err.println(),并将其打印到我的控制台。

有趣的是,如果我评论第一个assertThat,测试通过。 ?:(

那么,我如何嘲笑一个私有的方法,以便它不被调用?

import static org.hamcrest.core.Is.is;

import static org.junit.Assert.assertThat;

import static org.mockito.Matchers.anyInt;

import static org.mockito.Matchers.anyString;

import static org.powermock.api.mockito.PowerMockito.when;

import static org.powermock.api.support.membermodification.MemberMatcher.method;

import java.util.Random;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.powermock.api.mockito.PowerMockito;

import org.powermock.core.classloader.annotations.PrepareForTest;

import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)

@PrepareForTest(CodeWithPrivateMethod.class)

public class PowerMock_Test {

static boolean gambleCalled = false;

@Test(expected = RuntimeException.class)

public void when_gambling_is_true_then_always_explode() throws Exception {

CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());

when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))

.withArguments(anyString(), anyInt())

.thenReturn(true);

/* 1 */ assertThat( PowerMock_Test.gambleCalled, is(false) );

spy.meaningfulPublicApi();

/* 2 */ assertThat( PowerMock_Test.gambleCalled, is(false) );

}

}

class CodeWithPrivateMethod {

public void meaningfulPublicApi() {

if (doTheGamble("Whatever", 1 << 3)) {

throw new RuntimeException("boom");

}

}

private boolean doTheGamble(String whatever, int binary) {

Random random = new Random(System.nanoTime());

boolean gamble = random.nextBoolean();

System.err.println( "\n>>> GAMBLE CALLED <<

PowerMock_Test.gambleCalled = true;

return gamble;

}

}

^可以理解,由于我的工作区不支持JNDI,只有生产环境

%我正在使用最新版本的所有库,JUnit 4.10,Mockito 1.8.5,Hamcrest 1.1,Javassist 3.15.0和PowerMock 1.4.10。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值