几个概念
Mock
Stub
Spy
使用
多次调用返回不同的结果
1 when(mock.someMethod("some arg")) 2 .thenThrow(new RuntimeException()) // 第一次会抛出异常 3 .thenReturn("foo"); // 第二次会返回这个结果 4 //First call: throws runtime exception: 5 mock.someMethod("some arg"); // 第一次 6 //Second call: prints "foo" 7 System.out.println(mock.someMethod("some arg")); // 第二次 8 //Any consecutive call: prints "foo" as well (last stubbing wins). 9 System.out.println(mock.someMethod("some arg")); // 第n次(n> 2),依旧以最后返回最后一个配置
部分Mock - spy
3 //you can enable partial mock capabilities selectively on mocks: 4 Foo mock = mock(Foo.class); 5 //Be sure the real implementation is 'safe'. 6 //If real implementation throws exceptions or depends on specific state of the object then you're in trouble. 7 when(mock.someMethod()).thenCallRealMethod();
1 List list = new LinkedList(); 2 List spy = spy(list); 3 //optionally, you can stub out some methods: 4 when(spy.size()).thenReturn(100); 5 //using the spy calls *real* methods 6 spy.add("one"); 7 spy.add("two"); 8 //prints "one" - the first element of a list 9 System.out.println(spy.get(0)); 10 //size() method was stubbed - 100 is printed 11 System.out.println(spy.size()); 12 //optionally, you can verify 13 verify(spy).add("one"); 14 verify(spy).add("two");
Mock 依赖Bean
使用@InjectMocks,自动将模拟对象或侦查域注入到被测试对象中。
// FileService 依赖 FileDao @InjectMocks @Autowired private FileService fileService; @Mock private FileDao fileDao;
更多的使用方法可以参考Mockito浅谈