使用PowerMock模拟私有方法,但底层方法仍然被调用
我试图模拟一个进行JNDI调用的私有方法。当从单元测试调用该方法时,它会引发异常^。出于测试目的,我想模拟这种方法。我使用了另一个问题答案中的示例代码,当测试通过时,似乎仍然调用了基础方法。我在方法中插入了一个,它被打印出来到我的控制台上。System.err.println()
doTheGamble()
有趣的是,如果我注释掉第一个,测试通过。?:(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 <<<\n" );
PowerMock_Test.gambleCalled = true;
return gamble;
}
}
^ 可以理解的是,由于我的工作区不支持 JNDI,因此只有生产环境支持 JNDI
% 我正在使用所有库的最新版本,JUnit 4.10,Mockito 1.8.5,Hamcrest 1.1,Javassist 3.15.0和PowerMock 1.4.10。