私はJNDI呼び出しを行っているプライベートメソッドを嘲笑しようとしています。そのメソッドがユニットテストから呼び出されると、例外がスローされます。テスト目的でこのメソッドを模擬したいと思います。 sample code from another questions answerを使用しましたが、テストに合格している間は、基本的なメソッドが呼び出されたようです。 doTheGamble()
メソッドにSystem.err.println()
を挿入し、自分のコンソールに出力します。PowerMockでプライベートメソッドを偽装しましたが、基本的なメソッドがまだ呼び出されました
最初にassertThat
をコメントアウトすると、テストに合格します。 ?:(私のワークスペースにはJNDIをサポートしていないので、
だから、私はプライベートメソッドをモックんどのようにそれが呼び出されないように?
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;
}
}
は当然のことながら、唯一の生産環境が
を行います^%私はモックオブジェクトを構築するために、すべてのライブラリ、JUnitの4.10、Mockito 1.8.5、Hamcrest 1.1、Javassistの3.15.0、およびPowerMock 1.4.10。
+1はバグの無害です。あなたのことを大切にしています;) – Guillaume
@MikeなぜdoReturn(真)なのか、スパイ、doTheGamble、anyString()、anyInt()); 'doReturn(true).when(スパイ、メソッド(CodeWithPrivateMethod.class、 "doTheGamble"、String.class、int.class)).withArguments(anyString()、anyInt()); '結果は' IllegalArgumentException:引数型不一致 'になりますか?後者は、例のスタイルと少なくとも同等に保たれているように見えますが、機能しません。 – ArtB
正直、申し訳ありません。私は比較的Mockito/PowerMock自身に新しいです...私は以前にそのスタイル( '.withArguments(...)')でコードを書くことを試みたことはありません。 – Mike