Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

authenticate a user inside a test class

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    @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("user-jwt-controller@example.com");
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

>Solution :

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 {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading