目录

(三)如何做一些测试桩 (Stub)

何做一些测试桩 (Stub)


例子:

import org.junit.Test;

import java.util.LinkedList;

import static org.mockito.Mockito.*;



public class MockitoDemo {



    @Test(expected = RuntimeException.class)
    public void when_thenReturn(){
        //You can mock concrete classes, not only interfaces
        // 你可以mock具体的类型,不仅只是接口
        LinkedList mockedList = mock(LinkedList.class);

        //stubbing
        // 测试桩
        when(mockedList.get(0)).thenReturn("first");
        when(mockedList.get(1)).thenThrow(new RuntimeException());

        //following prints "first"
        // 输出“first”
        System.out.println(mockedList.get(0));

        //following throws runtime exception
        // 抛出异常
        System.out.println(mockedList.get(1));

        //following prints "null" because get(999) was not stubbed
        // 因为get(999) 没有打桩,因此输出null
        System.out.println(mockedList.get(999));

        //Although it is possible to verify a stubbed invocation, usually it's just redundant
        //If your code cares what get(0) returns then something else breaks (often before even verify() gets executed).
        //If your code doesn't care what get(0) returns then it should not be stubbed. Not convinced? See here.
        // 验证get(0)被调用的次数
        verify(mockedList).get(0);
    }

}
  • 默认情况下,所有的函数都有返回值。mock函数默认返回的是null,一个空的集合或者一个被对象类型包装的内置类型,例如0、false对应的对象类型为Integer、Boolean;

  • 测试桩函数可以被覆写 : 例如常见的测试桩函数可以用于初始化夹具,但是测试函数能够覆写它。请注意,覆写测试桩函数是一种可能存在潜在问题的做法;

  • 一旦测试桩函数被调用,该函数将会一致返回固定的值;

  • 上一次调用测试桩函数有时候极为重要-当你调用一个函数很多次时,最后一次调用可能是你所感兴趣的。

  • 在测试桩中预设get(1) 跑出 RuntimeException 异常; 在@Test() 中设置 expected = RuntimeException.class ,说明该异常为测试用例预期结果。

原始封面

https://images.unsplash.com/photo-1472289065668-ce650ac443d2?w=300