Mockito

2013-01-03T00:00:00+00:00 Java

どうもモック伊藤です。っていう鉄板ジョークはおいといて、Mockitoを使ってみた。でstaticメソッドのmockはPowerMockitoってのを使えば出来る模様なので

build.gradle

apply {
    plugin "java"
    plugin "eclipse"
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile "junit:junit:4.11"
    testCompile "org.hamcrest:hamcrest-all:1.3"
    testCompile "org.mockito:mockito-all:1.9.5"
    testCompile "org.powermock:powermock-mockito-release-full:1.5"
}

Mockito及びPowerMock関係の依存性を追加

Sample.java (テスト対象クラス)

あくまで使い方を前提なので適当に

package sample;

import java.util.ArrayList;
import java.util.List;

public class Sample {

    public static List<Integer> getNums() {
        return new ArrayList<Integer>() {
            {
                add(1);
                add(2);
                add(3);
            }
        };
    }

    public int sum() {
        List<Integer> nums = Sample.getNums();

        if (nums.size() <= 0) {
            throw new IllegalStateException();
        }

        int sum = 0;

        for (int n : nums) {
            sum += n;
        }

        return sum;
    }
}

SampleTestCase.java

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 sample.Sample;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;

@RunWith(PowerMockRunner.class)
@SuppressWarnings("all")
public class SampleTestCase {

    @Test
    public void test1() {
        Sample sample = new Sample();
        assertThat(sample.sum(), is(6)); // 普通に実オブジェクトをテスト
    }

    @Test
    public void test2() {
        List l = spy(new ArrayList());
        l.add("hoge");

        when(l.get(0)).thenReturn("fuga"); // List.get(0) をした際にはfugaが返される

        assertThat((String)l.get(0), is("fuga"));
    }

    @Test
    public void test3() {
        Sample sample = spy(new Sample());
        when(sample.sum()).thenReturn(1); // 実オブジェクト上のメソッドが返す値を書き換える

        assertThat(sample.sum(), is(1));
    }

    @Test
    public void test4() {
        Sample sample = mock(Sample.class);
        when(sample.sum()).thenThrow(IOException.class); // 実オブジェクト上のメソッドを実行すると例外を送出させる

        Throwable t = null;

        try {
            sample.sum();
        } catch (Exception e) {
            t = e;
        }

        assertNotNull(t);
        assertThat(t, instanceOf(IOException.class));
    }

    @Test
    @PrepareForTest(Sample.class)
    public void test5() {
        PowerMockito.mockStatic(Sample.class);

        // initNumsを実行するとIOExceptionが発生
        when(Sample.getNums()).thenThrow(IOException.class);

        Throwable t = null;

        try {
            Sample.getNums();
        } catch (Exception e) {
            t = e;
        }

        assertNotNull(t);
        assertThat(t, instanceOf(IOException.class));
    }

    // staticメソッドを書き換えて実オブジェクト上でそれを使った場合のテスト
    @Test
    @PrepareForTest(Sample.class)
    public void test6() {
        PowerMockito.mockStatic(Sample.class);

        when(Sample.getNums()).thenReturn(new ArrayList<Integer>());

        assertThat(Sample.getNums().size(), is(0));

        Throwable t = null;

        try {
            Sample sample = new Sample();
            sample.sum();
        } catch (Exception e) {
            t = e;
        }

        assertNotNull(t);
        assertThat(t, instanceOf(IllegalStateException.class));
    }
}

Mockitoの件 (2) Androidアプリ上でのサーチハードウェアキーによる振る舞い機能を実装