Mockito和junit做单元测试

简单入门

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();
    }
}

你可能感兴趣的:(测试)