junitsonarQube 测试覆盖率:如果条件

junit- sonarQube test coverage : if condition

你能帮我在这个方法中如何通过 junit 测试覆盖 if 语句吗:

这是我在控制器“用户”中的方法:

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

我的问题是 if 语句的两行,我不知道我想如何覆盖它们。

这是我对此方法的测试代码:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
ResponseEntity<Utilisateur> responseEntity16 = userController.getAllInformationAboutUser();
    
SecurityContextHolder.clearContext();
ResponseEntity<Utilisateur> responseEntity15 = userController.getAllInformationAboutUser();

提前感谢您的帮助

您需要创建一个临时Authentication信息

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

结果: