承接上文
********************************************
登录业务
java
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
@Resource
private JwtUtils jwtUtils;
@Override
public 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.签发token
String token = jwtUtils.createJwt(
employeeInDb.getId(),
null,
60*60*24*7L,
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
);
return token;
}
}
现要对这个登录业务进行测试,要测试的情况有 登录成功,账号或电话输入错误,密码输入错误三种情况
异常状态码
单元测试
通过断言对失败的情况进行判定,通过Assertions.assertEquals进行进一步判定异常的具体出错信息。
java
@SpringBootTest
public class EmployeeControllerTests {
@Resource
private EmployeeController employeeController;
@Test
//成功的情况
public void testLoginSuccess() {
Employee employee = new Employee();
employee.setUsername("admin");
employee.setPassword("123456");
}
@Test
public 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());
}
@Test
public 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());
}
}
测试结果