Home > Software engineering >  authenticate a user inside a test class
authenticate a user inside a test class

Time:04-08

I am new to spring boot and testing and I have spring boot app (generated with JHipster) that uses authentication. I need to get the id of the current user. so this method inside userRepository returns the current user

@Query(value = "select u.* from user u where u.username=?#{principal.username}", nativeQuery = true)
User findConnectedUser();

here is the method I want to test in my controller:

@PostMapping("/rdvs")
    public ResponseEntity<Rdv> createRdv(@RequestBody Rdv rdv) throws URISyntaxException {
        log.debug("REST request to save Rdv : {}", rdv);
        if (rdv.getId() != null) {
            throw new BadRequestAlertException("A new rdv cannot already have an ID", ENTITY_NAME, "idexists");
        }

        User user = userRepository.findConnectedUser();       
        rdv.setIdUser(user.getId());
      
        Rdv result = rdvRepository.save(rdv);
        return ResponseEntity
            .created(new URI("/api/rdvs/"   result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

here is my test method @Autowired private RdvRepository rdvRepository;

    @Autowired
    private UserRepository userRepository;

    ....

    @Test
        @Transactional
        void createRdv() throws Exception {
            int databaseSizeBeforeCreate = rdvRepository.findAll().size();
            // Create the Rdv        
            restRdvMockMvc
                .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(rdv)))
                .andExpect(status().isCreated());
    
            // Validate the Rdv in the database
    
            User user = userRepository.findConnectedUser();// this generate the NullPointer exception
    
            List<Rdv> rdvList = rdvRepository.findAll();
            assertThat(rdvList).hasSize(databaseSizeBeforeCreate   1);
            Rdv testRdv = rdvList.get(rdvList.size() - 1);
            assertThat(testRdv.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
            assertThat(testRdv.getIdUser()).isEqualTo(user.getId());
        }

So this method generate a NullPointer, I guess because the method can't find the current user which should be authenticated first. So how can I authenticate a user inside that test method please I spend a lot of time with it but nothing seems to be working

note: I tried to call this api that authenticate users

@PostMapping("/authenticate")
    public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            loginVM.getUsername(),
            loginVM.getPassword()
        );

        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = tokenProvider.createToken(authentication, loginVM.isRememberMe());
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer "   jwt);
        return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
    } 

like this in test method

User user = new User();
user.setLogin("user-jwt-controller");
user.setEmail("[email protected]");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));

userRepository.saveAndFlush(user);

LoginVM loginVM = new LoginVM();
loginVM.setUsername("user-jwt-controller");
loginVM.setPassword("test");
//I don't know how to call the api @PostMapping("/authenticate")

Thanks in advance

CodePudding user response:

Have a look at @WithMockUser annotation, see https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/test-method.html

You can see an example in the project that was generated by JHipster:

@AutoConfigureMockMvc
@WithMockUser(value = TEST_USER_LOGIN)
@IntegrationTest
class AccountResourceIT {
  • Related