Mockito框架使用
2021-01-05 本文已影响0人
supremecsp
Mockito框架是单元测试处理bean依赖注入的一大利器
@Data
@Builder
public class User {
private Longid;
private Stringname;
}
@Repository
public class UserDao {
public User getUser(Long id){
return User.builder().id(id).name("user").build();
}
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User getUser(Long id) {
return userDao.getUser(id);
}
}
省略UserService ,此时正常编写测试类的话会加载Spring的依赖
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoTest {
@Autowired
private UserService userService;
@Test
public void test() {
User user = userService.getUser(1L);
Assert.assertEquals("user",user.getName());
}
}
image.png
Mockito的出现,可以自由自定义数据,方便日常单元测试
public class DemoTest {
@Test
public void test() {
UserService userService = mock(UserService.class);
when(userService.getUser(any(Long.class))).thenReturn(User.builder().id(1L).name("user").build());
User user = userService.getUser(1L);
System.out.println(user);
Assert.assertEquals("user",user.getName());
}
}
或者
public class DemoTest {
@Mock
private UserService userService;
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Test
public void test() {
when(userService.getUser(any(Long.class))).thenReturn(User.builder().id(1L).name("user from mock").build());
User user = userService.getUser(1L);
System.out.println(user);
Assert.assertEquals("user",user.getName());
}
}
启动无需加载spring,很快跑完单元测试
Mockito一些常用方法
//输入任何Long类型的参数,返回值都为thenReturn中的值
when(userService.getUser(anyLong())).thenReturn(User.builder().id(1L).name("user").build());
//当输入参数为22L时,返回值为thenReturn中的值
when(userService.getUser(argThat(arg -> 22L==arg))).thenReturn(User.builder().id(1L).name("user").build());
//校验getUser方法是否被调用,verify也可检验调用次数
verify(userService).getUser(1L);
//spy局部mock
List list = new LinkedList();
List spy = spy(list);
when(spy.size()).thenReturn(100);
spy.add("one");
System.out.println(spy.size());//100 is printed