이제 테스트를 진행하면 TestUserDetailsService 파일이 돌게된다.
무조건 ssar 1234 ssar@nate.com이 실제 세션에 담기게 된다. mock가 아님
테스트에 세션값이 필요할 때마다 WithUserDetails를 붙여주면 된다.
프로필 이미지 업데이트 테스트를 해보자.
본코드에서 받아오는 데이터는 loginUser와 MultipartFile이다.
이 컨트롤러에서는 접근을 위한 인증만 필요한게 아니라 세션값을 사용해야하기 때문에
@WithUserDetails("ssar")을 붙여주자.
세션에 접근하기 위해 다음과 같이 해준다.
// given
// 세션에 접근하기
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
값이 필요하면 위와 같이 찾아주면 되고, 실제 컨트롤러를 때릴 때 @WithUserDetails가 loginUser를 알아서 넣어줄 것이다.
given 값은 MultipartFile 데이터를 만들어주면 된다.
nullpointerException이 뜬다.
뭐가 잘못된건지 처음부터 하나씩 짚어보자.
잘 넘겼다고 생각한 loginUser가 잘 들어간게 맞나 확인해보자.
본코드를 잠시 수정할것이다.
@PutMapping("/s/api/user/profile-img")
public String profileImgUpdate(@AuthenticationPrincipal LoginUser loginUser,
MultipartFile profileImgFile) {
System.out.println("==================================");
System.out.println(loginUser.getUser().getUsername());
System.out.println("==================================");
return "1";
}
ssar이 뜨기 때문에 세션은 잘 들어가고 있는게 확인됐다.
두번째로 본코드에서 서비스로 세션을 넘겨야하는데 이 세션은 HttpSession이다.
사진이 변경되면 세션값을 바꿔주기 위해 세션값을 넘겼었다.
서비스에서 세션을 만지는건 좋지않다.
세션 값을 변경하고 싶다면 어떤 결과를 리턴받아서 컨트롤러에서 변경하는게 좋다.
세션이 null이라고 오류가 뜨진않는다.
실제로 setAttribute를 하려고 할 때 null이면 오류가 터질 것이다.
@PutMapping("/s/api/user/profile-img")
public String profileImgUpdate(@AuthenticationPrincipal LoginUser loginUser,
MultipartFile profileImgFile) {
System.out.println("==================================");
session.setAttribute("principal", "hello");
System.out.println("==================================");
return "1";
}
잘 넘어간다.
이제 profileImgFile만 확인하면 되겠다.
실제로 멀티파트파일에 실제 이미지 파일이 들어온다.
[Spring/Blog-V3] - 단위테스트시 MultipartFile 만드는 법
패스에 윈도우는 역슬래시 2개씩 써준다
put으로 바꾸기 위해 해당 코드가 필요하다.
MockMultipartHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart("/s/api/user/profile-img");
builder.with(new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.setMethod("PUT");
return request;
}
});
결국 모크 멀티파트파일을 만들기 위해서는 코드 두줄이면 끝난다.
// given
File file = new File(
"C:\\workspace\\repositories\\spring_lab\\blogv3\\src\\main\\resources\\static\\images\\dog.jpg");
MockMultipartFile image = new MockMultipartFile("profileImgFile", "dog.jpg", "image/jpeg",
Files.readAllBytes(file.toPath()));
다시 컨트롤러 본코드 원상복구 해두고 when, then만 체크해보자.
// when
ResultActions resultActions = mockMvc.perform(
builder.file(image));
// then
resultActions
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
모두 잘 통과한다.
패스워드 리셋 테스트는
실제로 이메일 계정을 테스트 설정파일에 넣어주든지, 스텁처리하든지.