承接上文
统一异常处理,封装结果-CSDN博客
********************************************
登录业务
@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());}}
测试结果