相关文章推荐
  • mock测试就是在测试过程中,对那些不容易构建的对象用一个虚拟对象来代替测试的方法就叫mock测试。
  • 添加依赖

    1
    2
    //Mockito-all测试框架
    compile group: 'org.mockito', name: 'mockito-all', version: '2.0.2-beta'
  • 需要在@Before注解的setUp()中进行初始化(下面这个是个测试类的基类)
  • 1
    2
    3
    4
    5
    6
    7
    public abstract class MockitoBasedTest {
    @Before
    public void setUp() throws Exception {
    // 初始化测试用例类中由Mockito的注解标注的所有模拟对象
    MockitoAnnotations.initMocks(this);
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @Test
    public void toIndex() throws Exception {
    List<String> list = Mockito.mock(List.class);
    //设置方法预期返回值 【√】
    Mockito.when(list.get(0)).thenReturn("helloworld");
    //设置方法的预期返回值 不推荐不如上一种方式 可读性不高 【X】
    Mockito.doReturn("secondhello").when(list).get(1);
    String str = list.get(0);
    //验证方法调用(是否调用了get(0))
    Mockito.verify(list).get(0);
    //junit测试
    Assert.assertEquals(str, "helloworld");
    }

    创建mock对象不能对 final Anonymous (匿名类) primitive (基本数据类型如int、double等和包装类) 类进行mock。

    如果mock的话,会给你一个红灯:

    1
    2
    3
    4
    5
    6
    org.mockito.exceptions.base.MockitoException:
    Cannot mock/spy class java.lang.Integer
    Mockito cannot mock/spy following:
    - final classes
    - anonymous classes
    - primitive types
  • 设置方法设定返回异常
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @Test
    public void toIndex() throws Exception {
    //创建mock对象,参数可以是类,也可以是接口
    List<String> list = Mockito.mock(List.class);
    //设置方法设定返回异常
    Mockito.when(list.get(1)).thenThrow(new RuntimeException("这是类型的错误"));
    String result = list.get(1);
    //junit测试
    Assert.assertEquals("helloworld", result);
    }
  • 没有返回值的void方法与其设定(支持迭代风格,第一次调用donothing,第二次dothrow抛出runtime异常)
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    @Test
    public void toIndex() throws Exception {
    //创建mock对象,参数可以是类,也可以是接口
    List<String> list = Mockito.mock(List.class);
    Mockito.doNothing().doThrow(new RuntimeException("void exception")).when(list).clear();
    list.clear();
    System.out.println("第一次调用完");
    list.clear();
    System.out.println("第二次调用完");
    // Mockito.times(N) 调用N次
    Mockito.verify(list,Mockito.times(2)).clear();
    }

    参数匹配器(Argument Matcher)

     
    推荐文章