@WebMvcTest 403 error

nero·2023년 3월 28일
0
post-thumbnail

문제

  • webMvcTest 도중에 발생한 문제
  • controller 테스트를 만들다가 문제를 만났습니다. update 를 patch 매핑 문제입니다.

문제가 발생한 코드

// when
ResultActionsactions = mockMvc.perform(patch("/api/diary/{id}", 1L)
        .content(json)
        .contentType(APPLICATION_JSON));
// then
actions.andExpect(status().isOk())
        .andDo(print());

문제가 error 내용

java.lang.AssertionError: Status expected:<200> but was:<403>
Expected :200
Actual   :403
<Click to see difference>

at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
	at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
	at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
	at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:214)
	at nero.diary.domain.diary.api.DiaryApiControllerTest.update(DiaryApiControllerTest.java:200)

해결

  • .with(csrf()) 코드를 추가
// when
ResultActionsactions = mockMvc.perform(patch("/api/diary/{id}", 1L)
				// add !!
				.with(csrf())
				//
        .content(json)
        .contentType(APPLICATION_JSON));
// then
actions.andExpect(status().isOk())
        .andDo(print());

원인

  • Spring Security가 기본적으로 CSRF 공격 방지하는 기능을 수행하는데 테스트 과정에서 다른 사이트의 요청으로 인지한 것

✨ 정확한 원인, 해결법은 아니고 이외 틀린거 있으면 지적과 참고만 해주시길바랍니다

profile
겸손하게 배우는 개발자입니다

0개의 댓글