TIL
(2024-06-17) 개인과제 컨트롤러 테스트
o_coding
2024. 6. 18. 16:25
@ExtendWith(SpringExtension.class)
@WebMvcTest(
controllers = {ProfileController.class, LikeController.class},
excludeFilters = {
@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
classes = WebSecurityConfig.class
)
}
)
@AutoConfigureMockMvc
class ProfileControllerTest {
private MockMvc mvc;
private Principal mockPrincipal;
@Autowired
WebApplicationContext context;
@Autowired
ObjectMapper objectMapper;
@MockBean
ProfileService profileService;
@MockBean
LikeService likeService;
private UserDetailsImpl mockUserDetails;
@BeforeEach
public void setUp(){
mockUserDetails = new UserDetailsImpl(mockUserSetUp());
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity(new MockSpringSecurityFilter()))
.build();
mockPrincipal = new UsernamePasswordAuthenticationToken(mockUserDetails,"",mockUserDetails.getAuthorities());
}
public User mockUserSetUp(){
//mock 테스트 유저 생성
String userId = "xjr279612@";
String password = "Xjr8406@123";
String username = "ddaw12";
String email = "ohs9902@naver.com";
String intro = "dawdawda12121";
User testUser = new User(userId,password,username,email,intro);
return testUser;
}
@Test
@DisplayName("프로필 조회 테스트")
public void testProfiileInquire() throws Exception {
//given
long id = 1L;
ProfileResponseDto profileResponseDto = new ProfileResponseDto(mockUserSetUp());
when(profileService.getProfile(id)).thenReturn(profileResponseDto);
//when - then
mvc.perform(MockMvcRequestBuilders.get("/api/profile/{id}",id))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.userId").value("xjr279612@"))
.andExpect(jsonPath("$.name").value("ddaw12"))
.andExpect(jsonPath("$.email").value("ohs9902@naver.com"))
.andExpect(jsonPath("$.intro").value("dawdawda12121"));
}
@Test
@DisplayName("프로필 업데이트 테스트 ")
public void testUpdateProfile() throws Exception {
//given
User testUser = mockUserDetails.getUser();
ProfileRequestDto requestDto = new ProfileRequestDto();
requestDto.setUserId(testUser.getUserId());
requestDto.setPassword(testUser.getPassword());
requestDto.setEmail(testUser.getEmail());
requestDto.setId(0);
requestDto.setName("수정된 이름");
requestDto.setIntro("수정된 소개 ");
ProfileResponseDto responseDto = new ProfileResponseDto(testUser.getUserId(),"수정된 이름", testUser.getEmail(),"수정된 소개");
when(profileService.update(any(UserDetailsImpl.class),any(ProfileRequestDto.class)))
.thenReturn(responseDto);
//when - then
mvc.perform(put("/api/profile")
.principal(mockPrincipal)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(requestDto)))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.userId").value("xjr279612@"))
.andExpect(jsonPath("$.name").value("수정된 이름"))
.andExpect(jsonPath("$.email").value("ohs9902@naver.com"))
.andExpect(jsonPath("$.intro").value("수정된 소개"));
}
@Test
@DisplayName("비밀번호 변경 테스트")
public void testPasswordUpdate() throws Exception {
//given
ProfileRequestDto requestDto = new ProfileRequestDto();
requestDto.setNewPassword("newPassword4321@");
doNothing().when(profileService).updatePassword(any(UserDetailsImpl.class),any(ProfileRequestDto.class));
//when - then
mvc.perform(put("/api/profile/password")
.principal(new UsernamePasswordAuthenticationToken(mockUserDetails,null))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(requestDto)))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().string("비밀번호가 변경되었습니다."));
}
}
프로필 컨트롤러 테스트
MockMvc를 사용해서 http 요청을 테스트할 수있다. 그리고
컨트롤러 테스트를 위해서는 가짜 인증 필터가 필요하다
public class MockSpringSecurityFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
SecurityContextHolder.getContext()
.setAuthentication((Authentication) ((HttpServletRequest) req).getUserPrincipal());
chain.doFilter(req, res);
}
@Override
public void destroy() {
SecurityContextHolder.clearContext();
}
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
SecurityContextHolder.getContext()
.setAuthentication((Authentication) ((HttpServletRequest) req).getUserPrincipal());
chain.doFilter(req, res);
}
@Override
public void destroy() {
SecurityContextHolder.clearContext();
}
}
가짜 필터를 이용해서 사용자 정보를 쉽게 등록하고 테스트 할 수 있다.