承接上文
统一异常处理,封装结果-CSDN博客
********************************************
为什么需要进行单元测试?单元测试有什么作用?
单元测试是软件开发过程中不可或缺的一部分,它对于确保代码质量、提高开发效率、促进团队协作以及降低维护成本等方面都起着至关重要的作用。以下是进行单元测试的几个主要原因:
1.提高代码质量
2.促进快速反馈
3.降低维护成本
4.增强代码的可读性和可维护性
.......
*****************************************
下面为一个登录接口进行单元测试
登录业务
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {@Resourceprivate JwtUtils jwtUtils;@Overridepublic String login(Employee employee) {//2.构造条件LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();wrapper.eq(Employee::getUsername,employee.getUsername()).or().eq(Employee::getPhone,employee.getPhone());//1. 根据用户名或者密码查询用户信息Employee employeeInDb = this.getOne(wrapper);//3.判断是否查询到用户if(employeeInDb == null){throw new BusinessException(ResponseEnum.USER_INVALID);}//4.比较密码if(!BCrypt.checkpw(employee.getPassword(),employeeInDb.getPassword())){throw new BusinessException(ResponseEnum.PASSWORD_INVALID);}//5.签发tokenString token = jwtUtils.createJwt(employeeInDb.getId(),null,60*60*24*7L,"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");return token;}
}
现要对这个登录业务进行测试,要测试的情况有 登录成功,账号或电话输入错误,密码输入错误三种情况(当然实际上肯定不止这三种情况)
异常状态码
单元测试
通过断言对失败的情况进行判定,通过Assertions.assertEquals进行进一步判定异常的具体出错信息。
@SpringBootTest
public class EmployeeControllerTests {@Resourceprivate EmployeeController employeeController;@Test//成功的情况public void testLoginSuccess() {Employee employee = new Employee();employee.setUsername("admin");employee.setPassword("123456");}@Testpublic void testLoginPasswordError() {//断言BusinessException e = Assertions.assertThrows(BusinessException.class, () -> {Employee employee = new Employee();employee.setUsername("admin");employee.setPassword("1234567");employeeController.login(employee);});//进一步断定更详细的异常类型Assertions.assertEquals("密码错误",e.getResponse().getMessage());}@Testpublic void testLoginUsernameError() {BusinessException e = Assertions.assertThrows(BusinessException.class, () -> {Employee employee = new Employee();employee.setUsername("adminaa");employee.setPassword("123456");employeeController.login(employee);});Assertions.assertEquals("用户不存在",e.getResponse().getMessage());}}
直接启动测试类,查看测试结果
全绿表示我们的断言全部正确,测试通过