Mock测试
Mockito allows to configure the return values of its mocks via a fluent API. Unspecified method calls return "empty" values:
- null for objects
- 0 for numbers
- false for boolean
- empty collections for collections
利用ArgumentCaptor(参数捕获器)捕获方法
参数进行验证通过 ArgumentCaptor 对象的forClass(Classclazz)方法来构建ArgumentCaptor对象。然后便可在验证时对方法的参数进行捕获,最后验证捕获的参数值。如果方法有多个参数都要捕获验证,那就需要创建多个ArgumentCaptor对象处理。 当某个对象进行了多次调用后,比如mock对象。这时调用argument.getValue()获取到的是最后一次调用的参数。如果要获取所有的参数值可以调用argument.getAllValues(),它将返回参数值的List
@Test public void testArgumentCaptor() { when(userDao.findByUser("hs", "123")).thenReturn(new User("hs", "123")); when(userDao.findByUser("ys", "321")).thenReturn(new User("ys", "321")); assertThat(userService.findByUser("hs", "123"), is(new User("hs", "123"))); assertThat(userService.findByUser("ys", "321"), is(new User("ys", "321"))); ArgumentCaptorcaptor = ArgumentCaptor.forClass(String.class); verify(userDao, times(2)).findByUser(captor.capture(), captor.capture()); System.out.println(captor.getValue()); System.out.println(captor.getAllValues()); }
321[hs, 123, ys, 321]
unit -mock without autowire
In Spring Boot applications, by using Mockito, you replace the @Autowired components in the class you want to test with mock objects.