我试图嘲笑模拟一个正在进行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( …Run Code Online (Sandbox Code Playgroud)