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をサポートしていないため、実稼働環境のみがサポートしています。
%すべてのライブラリの最新バージョンであるJUnit 4.10、Mockito 1.8.5、Hamcrest 1.1、Javassist 3.15.0、およびPowerMock1.4.10を使用しています。