Junit4 + PowerMockでユニットテストを書いている際に、対象クラスの一部staticメソッドのみをモック化してテストしたかったのですが、mockStatic
だと対象クラスの全てのstaticメソッドがモック化されてしまうのを、spy
を使うことで回避できたので記録します。
version
java11
pom.xml
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
テスト対象クラス
Sample.java
public class Sample {
public static void main() {
System.out.println(doSomething0());
System.out.println(doSomething1());
System.out.println(doSomething2());
}
public static String doSomething0() {
return "something0";
}
public static String doSomething1() {
return "something1";
}
public static String doSomething2() {
return "something2";
}
}
テストコード
SampleTest.java
@RunWith(PowerMockRunner.class)
@PrepareForTest(Sample.class)
public class SampleTest {
@Test
public void testSample() {
// mockStaticではなくspyを使うことで一部メソッドのみモック化
// PowerMockito.mockStatic(Sample.class);
PowerMockito.spy(Sample.class);
PowerMockito.when(Sample.doSomething1()).thenReturn("hello world");
Sample.main();
// 出力
// >> something0
// >> hello world
// >> something2
}
}
補足 : mockとspyの違い
mock
* 宣言時に全てのメソッドがモック化され、明示したメソッドのみ指定の振る舞い
* 明示していないメソッドは実行しても何も起きない
spy
* 宣言時にはメソッドのモック化はされず、明示したメソッドのみ指定の振る舞い
* 明示していないメソッドは通常通りの実行