摘要:本文主要介绍如何使用junit
来编写单元测试,包含mock
对象的方法和mock
静态方法使用案例,提高开发效率。
pom.xml
引入依赖包
springboot
引入依赖包
org.springframework.boot
spring-boot-starter-test
org.mockito
mockito-inline
test
普通java
项目
org.junit.jupiter
junit-jupiter
5.9.2
test
org.junit.vintage
junit-vintage-engine
5.9.2
test
org.mockito
mockito-core
4.11.0
test
org.mockito
mockito-junit-jupiter
4.11.0
test
org.mockito
mockito-inline
4.11.0
test
定义的类
UserEntity
@Data
@TableName("user")
public class UserEntity {
@TableId
private String id;
private String name;
private String address;
private Date createTime;
}
UserUtils
作为被
mock
的静态类
public class UserUtils {
public static UserEntity getUser(){
return new UserEntity();
}
public static boolean checkName(String name){
UserEntity userEntity = getUser();
return userEntity.getName().equals(name);
}
}
UserService
mock
的测试类
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@SDS("dynamic_member")
@Transactional(rollbackFor = Exception.class)
public UserEntity add(UserEntity userEntity) throws Exception{
userEntity.setId(IdWorker.getIdStr());
userEntity.setCreateTime(new Date());
userMapper.insert(userEntity);
return userEntity;
}
public UserEntity getLoginUser(){
return UserUtils.getUser();
}
public boolean checkName(String name){
boolean result = UserUtils.checkName(name);
System.out.println(result);
return result;
}
}
单元测试
UserServiceTest
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
/** mock静态类 */
private static MockedStatic userUtils;
/** mock被测试的类 */
@InjectMocks
private UserService userService;
/** mock注入的类 */
@Mock
private UserMapper userMapper;
@BeforeAll
static void init(){
userUtils = Mockito.mockStatic(UserUtils.class);
}
@Test
void add() throws Exception {
// mock方法中调用的其他方法
Mockito.when(userMapper.insert(Mockito.any())).thenReturn(1);
UserEntity result = userService.add(new UserEntity());
assertNotNull(result.getId());
}
@Test
void getLoginUser() {
UserEntity userEntity = new UserEntity();
userEntity.setName("zhangsan");
// mock无参静态方法
userUtils.when(UserUtils::getUser).thenReturn(userEntity);
UserEntity result = userService.getLoginUser();
assertEquals("zhangsan",result.getName());
}
@Test
void checkName() {
// mock有参数静态方法
userUtils.when(() -> UserUtils.checkName(Mockito.anyString())).thenReturn(true);
boolean result = userService.checkName("zhangsan");
assertTrue(result);
// mock有参数静态方法
userUtils.when(() -> UserUtils.checkName(Mockito.anyString())).thenReturn(false);
result = userService.checkName("zhangsan");
assertFalse(result);
}
}
测试结果
符合我们得预期结果