jhipster中的测试方法实现

时间:2017-11-03 00:12:22

标签: jhipster

我需要实现一个测试方法来涵盖以下方法。但并不是必须以100%的覆盖率来覆盖它。

@DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@Timed
@Secured({AuthoritiesConstants.ADMIN, AuthoritiesConstants.STUDENT})
public ResponseEntity<Void> deleteUser(@PathVariable String login) {
    log.debug("REST request to delete User: {}", login);
    boolean hasAuthorityStudent = false;
    boolean hasAuthorityAdmin = false;
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    hasAuthorityAdmin = authorities.contains(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));
    hasAuthorityStudent = authorities.contains(new SimpleGrantedAuthority(AuthoritiesConstants.STUDENT));
    if (hasAuthorityAdmin) {
        // delete user
        userService.deleteUser(login);
        return ResponseEntity.ok().headers(HeaderUtil.createAlert("userManagement.deleted", login)).build();
    } else {
        //get the authorities of the user who is going to be deleted
        Optional<User> user = userService.getUserWithAuthoritiesByLogin(login);
        Set<Authority> currentUserAuthorities = user.get().getAuthorities();
        log.debug("REST request to delete User: {}", user);
        log.debug("REST request to delete Member: {}", currentUserAuthorities);
        boolean hasDeletedMembByStu = false;
        if (hasAuthorityStudent) {
            for (Authority auth : currentUserAuthorities) {
                // delete user if it is a student
                if (auth.getName().equals(AuthoritiesConstants.MEMBER)) {
                    userService.deleteUser(login);
                    hasDeletedMembByStu = true;
                }
            }
            if (hasDeletedMembByStu) {
                return ResponseEntity.ok().headers(HeaderUtil.createAlert("userManagement.deleted", login)).build();
            }
        }
        return ResponseEntity.badRequest()
            .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "AccessDenied", "Lecturer can delete only members"))
            .body(null);
    }
}

我使用4.8.2作为jhipster版本。我试过如下。

@Test
@Transactional
public void deleteUser() throws Exception {
    // Initialize the database
    userRepository.saveAndFlush(user);
    userSearchRepository.save(user);
    restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin())
        .contentType(TestUtil.APPLICATION_JSON_UTF8))
        .andExpect(status().isBadRequest());       
}

用ROLE_USER初始化用户。然后生成测试方法的构建失败,说java.lang.AssertionError:状态预期:&lt; 400&gt;但是:&lt; 500&amp; gt

1 个答案:

答案 0 :(得分:1)

您尚未登录,因此authentication为空,authentication.getAuthorities()会抛出NullPointerException。

要解决此问题,您需要像here一样应用Spring-Security,并为您的请求分配用户和角色,例如here

其他注意:您可以直接在控制器方法中获取主体,而不是调用SecurityContextHolder.getContext().getAuthentication()

ResponseEntity<Void> deleteUser(@PathVariable String login, Principal principal) {
    log.debug("REST request to delete User: {}", login);
    boolean hasAuthorityStudent = false;
    boolean hasAuthorityAdmin = false;
    if (principal != null) {
        Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();
        ...
相关问题