A.Wen
A.Wen

Reputation: 223

Test Method Implementation in jhipster

I need to implement a test method to cover the following method. But it is not compulsory to cover it for 100% coverage.

@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);
    }
}

I an using 4.8.2 as the jhipster version. I have attempted as follows.

@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());       
}

There user is initialized with ROLE_USER. Then generated a build failure of the test method saying java.lang.AssertionError: Status expected:<400> but was:<500&gt

Upvotes: 0

Views: 320

Answers (1)

Christophe Bornet
Christophe Bornet

Reputation: 1127

You are not logged in so authentication is null and authentication.getAuthorities() throws a NullPointerException.

To fix that you need to apply Spring-Security like here and assign a user and roles to your request like here.

Other note : instead of calling SecurityContextHolder.getContext().getAuthentication() you can get the principal directly in the controller method :

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();
        ...

Upvotes: 1

Related Questions