mockitoでstaticなメソッドをMock化する


PowerMockを使用する

mockitoでstaticメソッドはMock化できないのでPowerMockを使用する。

ソース

テスト対象クラス

MoriUtilA.java
public class MoriUtilA {
    public static String getMoriString(String inStr){
        return "あなたは" + MoriUtilB.isMoriorHayashi(inStr) + "です";
    }
}

モック化するクラス

MoriUtilB.java
public class MoriUtilB {
    public static String isMoriorHayashi(String inStr){
        // 入力値が「もり」なら「森」を、それ以外なら「林」を返す
        return "";// 未作成
    }
}

インポート文

import static org.powermock.api.mockito.PowerMockito.when;
import org.junit.Before;
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;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;

テストクラス

MoriUtilATest.java
@RunWith(PowerMockRunner.class)
@PrepareForTest({MoriUtilB.class})
public class MoriUtilATest {
    @Before
    public void setUp() throws Exception {
        // MoriUtilBをモック
        PowerMockito.mockStatic(MoriUtilB.class);
    }
    @Test
    public void mockTestMori() {
        // モックの返却値を設定
        when(MoriUtilB.isMoriorHayashi("もり")).thenReturn("森");
        // 実施
        String actual = MoriUtilA.getMoriString("もり");
        assertEquals("あなたは森です", actual);
    }
    @Test
    public void mockTestHayashi() {
        // モックの返却値を設定
        when(MoriUtilB.isMoriorHayashi(anyString())).thenReturn("林");
        // 実施
        String actual = MoriUtilA.getMoriString("林");
        assertEquals("あなたは林です", actual);
    }
}

pom.xml

pom.xml
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.9.5</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <scope>test</scope>
    </dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.5.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.5.4</version>
    <scope>test</scope>
</dependency>