TroubleShooting

[junit] Auditor must not be null! Returned by: class com.example.demo.db.LoginUserAuditorAware!

에디개발자 2020. 12. 4. 07:00
반응형

Junit 테스트 코드를 작성하는 도중 Auditor must not be null 에러가 발생하였습니다.

나를 닮았다고 한다....

 

증상

Junit 테스트 할 로직 중 SecurityContext 정보를 조회할 필요가 있었습니다.

그래서 @BeforeEach 메서드에서 SecurityContext를 Mock으로 임의의 데이터를 넣고 @Test를 실행하는 경우였습니다.

@BeforeEach
void setUp() {
    // SecurityContext에서 가져올 유저 정보
    UserVo userVo = new UserVo();
    userVo.setUserId(1L);
    List<String> roleNames = Arrays.asList("ROLE_ADMIN");
    
    // userDetails Mock 설정
    UserDetails userDetails = new UserDetails(userVo, roleNames);
    Authentication authentication = Mockito.mock(Authentication.class);
    Mockito.when(authentication.getPrincipal()).thenReturn(payrollUserDetails);
    
    // SecurityContext Mock 설정
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
}
@Test를 하기 전 SecurityContext에 Mock Data(유저 정보)를 설정하는 소스입니다.

 

에러가 발생하는 부분을 따라들어가다 보니 아래 소스에서 에러가 발생하고 있었습니다.

authentication.isAuthenticated() 에서 에러가 발생하고 있었습니다
@Component
public class LoginUserAuditorAware  implements AuditorAware<String> {

	@Override
    public Optional<Long> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null == authentication || !authentication.isAuthenticated()) {  // 에러 발생지점
            return null;
        }
        UserDetails user = (UserDetails) authentication.getPrincipal();
        return Optional.of(user.getUserId());
    }

}
JPA Entity에서 createUserId에 @CreateBy를 사용하면 createUserId에 SecurityContext userId 정보를 설정합니다

 

원인

authentication.isAuthenticated() 에 대한 Mock Data 설정이 되어있지않아서 발생하는 문제였습니다.

 

 

해결

authentication.isAuthenticated() 에 대해서 Mock 설정을 해주어서 문제를 해결합니다.

@BeforeEach
void setUp() {
    // SecurityContext에서 가져올 유저 정보
    UserVo userVo = new UserVo();
    userVo.setUserId(1L);
    List<String> roleNames = Arrays.asList("ROLE_ADMIN");
    
    // userDetails Mock 설정
    UserDetails userDetails = new UserDetails(userVo, roleNames);
    Authentication authentication = Mockito.mock(Authentication.class);
    Mockito.when(authentication.getPrincipal()).thenReturn(payrollUserDetails);
    Mockito.when(authentication.isAuthenticated()).thenReturn(true);  // 추가
    
    // SecurityContext Mock 설정
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
}

 

 

반응형