can you help me how I can cover if statement by junit test in this method:
This is my Method in the controller “User” :
@GetMapping(value = "/informationUser") public ResponseEntity<Utilisateur> getAllInformationAboutUser() { Utilisateur user = null; // Fully covered By tests Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // Fully covered By tests if (authentication != null) { // Partially covered by Tests user = userService.findUserByLogin(authentication.getName()); // Not covered by Tests } return new ResponseEntity<>(user, HttpStatus.OK); Fully covered By tests }
My problem is with the 2 lines of the if statment, I don’t know how i want to cover them.
This is my test code for this method :
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ResponseEntity<Utilisateur> responseEntity16 = userController.getAllInformationAboutUser(); SecurityContextHolder.clearContext(); ResponseEntity<Utilisateur> responseEntity15 = userController.getAllInformationAboutUser();
Thank you in advance for your help
Advertisement
Answer
You need to create a temporary Authentication
information
@Test public void getAllInformationAboutUserTest() { // If you use Mockito -> Mockito.mock(Authentication.class) SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("foo", "bar")); ResponseEntity<Utilisateur> responseEntity16 = userController.getAllInformationAboutUser(); SecurityContextHolder.clearContext(); ResponseEntity<Utilisateur> responseEntity15 = userController.getAllInformationAboutUser(); }