java mocked_java – 使用PowerMock的Mocked私有方法,但是底层方法仍然被调用
我試圖嘲笑嘲弄一個(gè)正在進(jìn)行JNDI呼叫的私有方法。當(dāng)從單元測(cè)試中調(diào)用該方法時(shí),會(huì)拋出異常^。我想嘲笑這種方法進(jìn)行測(cè)試。我使用了
sample code from another questions answer,而測(cè)試通過(guò),似乎底層方法仍然被調(diào)用。我在doTheGamble()方法中插入了一個(gè)System.err.println(),并將其打印到我的控制臺(tái)。
有趣的是,如果我評(píng)論第一個(gè)assertThat,測(cè)試通過(guò)。 ?:(
那么,我如何嘲笑一個(gè)私有的方法,以便它不被調(diào)用?
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;
}
}
^可以理解,由于我的工作區(qū)不支持JNDI,只有生產(chǎn)環(huán)境
%我正在使用最新版本的所有庫(kù),JUnit 4.10,Mockito 1.8.5,Hamcrest 1.1,Javassist 3.15.0和PowerMock 1.4.10。
總結(jié)
以上是生活随笔為你收集整理的java mocked_java – 使用PowerMock的Mocked私有方法,但是底层方法仍然被调用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 微信中禁止网页下拉出现网页由XXX提供
- 下一篇: Ae:摄像机命令