Mockitoの件 (2)

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

引き続き、Mockitoのドキュメント読みつつ色々やってみた

import java.io.IOException;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
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("unchecked")
public class SampleTestCase {

    @Spy // Mockito.spyを使わなくてもアノテーションでオッケーっぽい
    private Sample sample = new Sample();

    @Test
    public void test1() {
        List<String> l = mock(List.class);
        when(l.get(anyInt())) // Intな引数を取る
            .thenReturn("hoge") // 1回目はhogeを返す
            .thenReturn("fuga") // 2回目はfugaを返す
            .thenThrow(IOException.class); // 以降はIOExceptionをスローする

        assertThat(l.get(0), is("hoge"));
        assertThat(l.get(1), is("fuga"));

        Throwable t = null;

        try {
            l.get(2);
        } catch (Exception e) {
            t = e;
        }

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

        reset(l);

        assertNull(l.get(0));
    }

    @Test
    public void test2() {
        when(sample.sum()).thenReturn(999);

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

    @Test
    @PrepareForTest(Math.class)
    public void test3() {
        PowerMockito.mockStatic(Math.class);

        when(Math.sqrt(anyDouble())).thenAnswer(new Answer<Double>() {
            @Override
            public Double answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();

                assertThat(args.length, is(1));
                assertThat((Double)args[0], is(2.0));

                /* 実メソッドを呼びたい場合
                invocation.callRealMethod();
                 */

                return 0.0;
            }

        });

        assertThat(Math.sqrt(2.0), is(0.0));

    }
}

Mockito