通常,我们的接口是会作登录校验的,为了安全,有些接口甚至有权限校验,这样,通常的单元测试就很难通过,此处以第一种情况为例:
- 接口(在接口内调用了当前登录的用户信息,如果发现不存在则会抛出异常)
@PostMapping("/save")
public Object save (@RequestBody @Valid final UserPage userPage, final HttpServletRequest request) {
final User user = new User();
BeanUtils.copyProperties(userPage, user);
final Date now = new Date();
user.setUpdateTime(now);
if (user.getValidBeginTime() != null && user.getValidEndTime() != null && !user.getValidBeginTime().before(user.getValidEndTime())) {
throw new BusinessException(ExceptionEnum.EXECUTE_BASE_CHECK_EXCPTION.setExceptionMsg("有效开始时间不能晚于有效结束时间"));
}
//根据用户名判断是否已经存在该类型
User temp = userDao.queryByUserName(userPage.getUserName());
if (userPage.getId() != null) {
//修改
if (temp != null && !temp.getId().equals(user.getId())) {
systemLogService.add(request, Constant.SYSTEM_LOG_MODULE_USER, Constant.SYSTEM_LOG_TYPE_MODIFY, "修改用户信息失败");
throw new BusinessException(ExceptionEnum.EXECUTE_BASE_CHECK_EXCPTION.setExceptionMsg("数据已存在"));
}
temp = (User) userDao.queryById(userPage.getId() );
userDao.update(user);
systemLogService.add(request, Constant.SYSTEM_LOG_MODULE_USER, Constant.SYSTEM_LOG_TYPE_MODIFY, "修改用户信息");
} else {
//新增
//修改
if (temp != null) {
systemLogService.add(request, Constant.SYSTEM_LOG_MODULE_USER, Constant.SYSTEM_LOG_TYPE_MODIFY, "新增用户信息失败");
throw new BusinessException(ExceptionEnum.EXECUTE_BASE_CHECK_EXCPTION.setExceptionMsg("数据已存在"));
}
user.setCreateUserId(UserUtils.getCurrentUser().getId());
user.setCreateTime(now);
userDao.add(user);
systemLogService.add(request, Constant.SYSTEM_LOG_MODULE_USER, Constant.SYSTEM_LOG_TYPE_MODIFY, "新增用户信息");
}
return "保存成功";
}
public class UserUtils {
/**
* 获取当前用户信息
* @return
* @throws AuthChallengeException
*/
public static User getCurrentUser () {
final Subject subject = SecurityUtils.getSubject();
if (subject == null) {
throw new BusinessException(ExceptionEnum.EXECUTE_AUTHORICATION_EXCEPTION.setExceptionMsg("用户未登录,或登录已过期"));
} else {
final Session session = subject.getSession();
if (session == null) {
throw new BusinessException(ExceptionEnum.EXECUTE_AUTHORICATION_EXCEPTION.setExceptionMsg("用户未登录,或登录已过期"));
} else {
final User user = (User) session.getAttribute("user");
if (user == null) {
throw new BusinessException(ExceptionEnum.EXECUTE_AUTHORICATION_EXCEPTION.setExceptionMsg("用户未登录,或登录已过期"));
}
return user;
}
}
}
}
- 单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class BaseTest {
@Autowired
org.apache.shiro.mgt.SecurityManager securityManager;
@Autowired
WebApplicationContext webApplicationContext;
public MockMvc mockMvc;
private void login(String username, String password) {
final UsernamePasswordToken token = new UsernamePasswordToken(username, password);
final Subject subject = SecurityUtils.getSubject();
subject.login(token);
}
@Before
public void before() {
SecurityUtils.setSecurityManager(securityManager);
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
login("admin", null);
}
}
public class UserControllerTest extends BaseTest {
@Test
public void testSave() throws Exception {
final UserPage userPage = new UserPage();
userPage.setUserName("test@136.com");
userPage.setEmail("test@163.com");
userPage.setCompanyId(1);
userPage.setCompanyName("终端公司");
userPage.setName("测试");
userPage.setPhone("18874551022");
userPage.setRoleId(1);
userPage.setRoleName("系统管理员");
final String jsonStr = JSONObject.toJSONString(userPage);
final MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/user/save")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonStr)
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andReturn();
int status = mvcResult.getResponse().getStatus();
assertEquals(200, status);
}
}