Mockitoとjunitはユニットテストをします

19371 ワード

簡単な入門

import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.stubbing.Answer;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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

/**
 * @author weijun.zou
 * Create on 2017/12/26
 */
public class MockitoDemo {

    private Linked linked = mock(Linked.class);

    //1.verify:  
    @Test
    public void test11() {
        linked.add("a");
        verify(linked).add("a");
        verify(linked, times(1)).add("a");
        linked.add("a");
        linked.add("b");
        verify(linked, times(2)).add("a");
        verify(linked, times(1)).add("b");
    }

    @Test(expected = AssertionError.class)
    public void test12() {
        verify(linked).next();
    }

    //2.when().ThenReturn():  
    @Test
    public void test21() {
        when(linked.previous()).thenReturn("b");
        assertEquals("b", linked.previous());
        when(linked.next())
                .thenReturn("a")
                .thenReturn("c");
        assertEquals("a", linked.next());
        assertEquals("c", linked.next());
        assertEquals("c", linked.next());
    }

    @Test
    public void test22() {
        when(linked.elementOf(1)).thenReturn("a");
        when(linked.elementOf(2)).thenReturn("b");
        assertEquals("a", linked.elementOf(1));
        assertEquals("b", linked.elementOf(2));
        assertNull(linked.elementOf(3));
    }

    @Test(expected = RuntimeException.class)
    public void test23() {
        when(linked.next())
                .thenReturn("a")
                .thenThrow(new RuntimeException());
        assertEquals("a", linked.next());
        //runtimeException
        linked.next();
    }

    @Test
    public void test24() {
        when(linked.elementOf(anyInt()))
                .thenAnswer((Answer) invocation -> {
                    Object[] args = invocation.getArguments();
                    Method method = invocation.getMethod();
                    return method.getName() + ":" + Arrays.toString(args);
                });
        System.out.println(linked.elementOf(2));
        System.out.println(linked.elementOf(3));
        System.out.println(linked.elementOf(anyInt()));
    }

    //3.argThat:  
    @Test
    public void test31() {
        when(linked.elementOf(anyInt())).thenReturn("a");
        assertEquals("a", linked.elementOf(
                (int) (Math.random() * Integer.MAX_VALUE)));
        verify(linked).elementOf(anyInt());

        when(linked.add(argThat(e -> e.length() < 3))).thenReturn(true);
        assertTrue(linked.add("ab"));
        assertFalse(linked.add("abc"));
        verify(linked).add(eq("abc"));
    }

    //4.times:  
    @Test
    public void test41() {

        verify(linked, never()).add("0");

        linked.add("1");
        verify(linked, times(1)).add("1");

        linked.add("2");
        linked.add("2");
        verify(linked, times(2)).add("2");

        linked.add("3");
        linked.add("3");
        linked.add("3");
        verify(linked, atLeastOnce()).add("3");
        verify(linked, atLeast(2)).add("3");
        verify(linked, atMost(3)).add("3");
    }

    //5.doThrow:  
    @Test(expected = IndexOutOfBoundsException.class)
    public void test51() {
        doThrow(new IndexOutOfBoundsException())
                .when(linked).elementOf(-1);
        linked.elementOf(-1);
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void test52() {
        doThrow(new IndexOutOfBoundsException())
                .when(linked)
                .elementOf(argThat(i -> i < 0));
        linked.elementOf(-1);
    }

    //6.order:  
    @Test
    public void test61() {
        linked.next();
        linked.add("hello");
        linked.elementOf(1);
        InOrder inOrder = inOrder(linked);
        inOrder.verify(linked).next();
        inOrder.verify(linked).add("hello");
        inOrder.verify(linked).elementOf(1);
    }

    //7. linked 
    @Test
    public void test71() {
        verifyNoMoreInteractions(linked);
        verifyZeroInteractions(linked);
    }

    //8.spy:  
    @Test
    public void test81() {
        Linked linked = spy(new LinkedImpl());
        when(linked.elementOf(argThat(i -> i < 0 || i >= linked.size())))
                .thenReturn(null);
        linked.add("0");
        assertNull(linked.previous());
        verify(linked).elementOf(-2);
        assertNull(linked.next());
        verify(linked).elementOf(-1);
        assertEquals("0", linked.next());
        verify(linked).elementOf(0);
    }

    interface Linked {
        String next();

        String previous();

        boolean add(String element);

        String elementOf(Integer index);

        int size();

    }

    class LinkedImpl implements Linked {

        private Integer index = -1;
        private List list = new ArrayList<>();

        @Override
        public String next() {
            return elementOf(++index);
        }

        @Override
        public String previous() {
            return elementOf(--index);
        }

        @Override
        public boolean add(String element) {
            return list.add(element);
        }

        @Override
        public String elementOf(Integer index) {
            return index == null
                    ? ""
                    : list.get(index);
        }

        @Override
        public int size() {
            return list.size();
        }
    }
}

開発環境でmockitoを使用してテストを行います。

public class User {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public interface UserDao {
    User findUserById(int id);
    int count();
}
public interface UserService {
    User findUserById(int id);
    int count();
}
public class UserServiceImpl implements UserService {

    private int minId = 1;
    private int maxId = 9999;
    private int countCache = -1;
    private UserDao userDao;

    @Override
    public User findUserById(int id) {
        return (id >= minId && id <= maxId)
                ? userDao.findUserById(id)
                : null;
    }

    @Override
    public int count() {
        return countCache == -1
                ? countCache = userDao.count()
                : countCache;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

UserServiceImplのテスト:
import org.junit.Before;
import org.junit.Test;

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

/**
 * @author weijun.zou
 * Create on 2017/12/26
 */
public class UserServiceImplTest {

    private UserService userService;
    private UserDao userDao;
    private int count = 10;

    @Before
    public void setUp() {
        userDao = mock(UserDao.class);
        userService = new UserServiceImpl();
        ((UserServiceImpl) userService).setUserDao(userDao);
        when(userDao.count())
                .thenReturn(count);
        when(userDao.findUserById(1))
                .thenReturn(new User(1,"one"));
        when(userDao.findUserById(2))
                .thenReturn(new User(2,"two"));
    }

    @Test
    public void findUserById1() throws Exception {
        assertEquals("one",userService.findUserById(1).getName());
        assertEquals(2,userService.findUserById(2).getId());
        assertEquals(null,userService.findUserById(3));
        verify(userDao).findUserById(1);
        verify(userDao).findUserById(2);
        verify(userDao).findUserById(3);
    }

    @Test(expected = AssertionError.class)
    // 
    public void findUserById2(){
        assertEquals(null,userService.findUserById(-1));
        verify(userDao).findUserById(-1);
    }

    @Test
    public void count1() throws Exception {
        assertEquals(count,userService.count());
        verify(userDao).count();
    }

    @Test
    // count countCache 
    public void count2() throws Exception {
        assertEquals(count,userService.count());
        assertEquals(count,userService.count());
        verify(userDao,times(1)).count();
    }
}