inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링 기반 REST API 개발

API 인덱스 만들기

MockMvc를 활용하는 테스트에서 403 에러가 발생하는 문제

669

염지원 Yeom

작성한 질문수 1

0

안녕하세요 기선님,

강의를 따라하다가 잘 되지 않는 부분이 있어서 질문 남깁니다.

강의 내용과 정말 똑같이 따라치고 있는데--github의 코드와도 대조해보았습니다--이상하게 mockMvc를 통해 테스트를 하는 부분 전체에서 결과값이 403으로 떨어지네요.

구글링 해보니 @WebMvcTest를 사용하는 경우 webapplicationcontext를 가져오도록 하라는 가이드만 나오고, @AutoConfigureMockMvc를 사용하는 경우는 사례를 찾기가 좀 어렵습니다.

제가 어떤 부분을 좀 살펴보아야 할 지 도움을 주실 수 있을까요?

에러 메시지는 다음과 같습니다.

MockHttpServletRequest:

HTTP Method = POST

Request URI = /api/events/

Parameters = {}

Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/hal+json"]

Body = {"id":100,"name":"Spring","description":"REST API Development with Spring","beginEnrollmentDateTime":"2018-11-23T14:21:00","closeEnrollmentDateTime":"2018-11-24T14:21:00","beginEventDateTime":"2018-11-25T14:21:00","endEventDateTime":"2018-11-26T14:21:00","location":"강남역 D2 스타텁 팩토리","basePrice":100,"maxPrice":200,"limitOfEnrollment":100,"offline":false,"free":true,"eventStatus":"PUBLISHED"}

Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@553d828a}

Handler:

Type = null

Async:

Async started = false

Async result = null

Resolved Exception:

Type = null

ModelAndView:

View name = null

View = null

Model = null

FlashMap:

Attributes = null

MockHttpServletResponse:

Status = 403

Error message = Forbidden

Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]

Content type = null

Body =

Forwarded URL = null

Redirected URL = null

Cookies = []

MockHttpServletRequest:

HTTP Method = POST

Request URI = /api/events/

Parameters = {}

Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/hal+json"]

Body = {"id":100,"name":"Spring","description":"REST API Development with Spring","beginEnrollmentDateTime":"2018-11-23T14:21:00","closeEnrollmentDateTime":"2018-11-24T14:21:00","beginEventDateTime":"2018-11-25T14:21:00","endEventDateTime":"2018-11-26T14:21:00","location":"강남역 D2 스타텁 팩토리","basePrice":100,"maxPrice":200,"limitOfEnrollment":100,"offline":false,"free":true,"eventStatus":"PUBLISHED"}

Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@553d828a}

Handler:

Type = null

Async:

Async started = false

Async result = null

Resolved Exception:

Type = null

ModelAndView:

View name = null

View = null

Model = null

FlashMap:

Attributes = null

MockHttpServletResponse:

Status = 403

Error message = Forbidden

Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]

Content type = null

Body =

Forwarded URL = null

Redirected URL = null

Cookies = []

java.lang.AssertionError: Status

Expected :400

Actual :403

<Click to see difference>

at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)

at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)

at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)

at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)

at com.rest.api.events.EventControllerTests.createEvent_Bad_Request(EventControllerTests.java:151)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.base/java.lang.reflect.Method.invoke(Method.java:566)

at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)

at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)

at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)

at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)

at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)

at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)

at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)

at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)

at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)

at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)

at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)

at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)

at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)

at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)

at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)

at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)

at org.junit.runners.ParentRunner.run(ParentRunner.java:363)

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)

at org.junit.runner.JUnitCore.run(JUnitCore.java:137)

at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)

at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)

at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)

at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

java rest-api spring

답변 1

-1

백기선

스프링 시큐리티를 의존성에 추가한 뒤에 아무 설정도 하지 않아서 그럴거에요. 스프링 시큐리티를 빼거나, 커스텀 한 설정을 추가하셔야 합니다. 제 강의를 순차적으로 잘 봐주세요. 그래도 안되면 메시지 주시구요.

Spring 시큐리티 관련해서 WebSecurityConfigurationAdapter

0

73

1

junit5 사용하시는 분들

0

88

1

자바 빈 스펙을 준수하는지 체크하는 테스트

0

238

2

REST API 개발 중 비즈니스 로직 적용 부분의 JSON 에러

0

243

1

스프링 부트 3버전에서의 실습

0

190

1

java.lang.AssertionError: Status

0

532

2

spring doc 관련 파일 생성 관련 배포 관련 질문 드립니다.

0

287

1

섹션2 201응답받기 부분 테스트 404에러 질문입니다

0

741

1

강의 자료가 404입니다 확인 부탁 드려요!

0

477

1

연동 DB문의

0

358

1

이벤트 Repository강의 중 Event 클래스에 private Integer Id; 위치 질문

0

505

1

(Mac) postgressql 관련하여 port kill 해도 다시 살아나는 경우

0

380

0

maven으로 생성한 docs파일(index.html)에서의 not found 오류 질문

0

621

1

테스트 오류 질문드립니다.

0

512

1

docs 요청값이 반영이 안되네요... (해결)

-1

394

1

psql 적용 후 에러

0

819

2

mvn package 시 다음과 같은 에러가 나시면

0

765

2

Event에 Account manager를 추가했으면 문서화 필요

0

274

1

2년 훨씬 전 부터 Restlet-> Talend API 로 바뀌었습니다~

1

473

1

asciidoc 추가 스니펫 에러 해결법

0

400

1

_links 는 현재 fieldWithPath 를 해주지 않아도 됩니다.

0

424

3

깃랩 처음 사용자를 위한 index.adoc raw 보는 법

0

332

1

eclipse 쓰시는 분을 위한 maven-resources-plugin 팁

0

333

1

부트 + jupiter 인 경우 설정법

0

342

1