package com.kelly.springbootkelly.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello";
}
}
RestController
- 컨트롤러를 JSON을 반환한는 컨트롤러로 만들어 줌
- @ResponseBOdy를 각 메소드마다 선언했던것을 한번에 사용할 수 있게 해준다고 생각하면됨.
@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void hello_will_return() throws Exception {
String hello = "hello";
RequestBuilder builder = MockMvcRequestBuilders.get("/hello");
mvc.perform(builder)
.andExpect(content().string(hello))
.andExpect(status().isOk());
}
}
ExtendWith
- 테스트를 진행할 때 JUnit에 내장된 실행자 외에 다른 실행자를 실행함.
- 여기서는 SpringExtensiondㅣ라는 스프링 실행자를 사용
- 즉, 스프링 부트 테스트와 JUnit사이에 연결자 역할을 함.
WebMvcTest
- 여러 스프링 테스트 어노테이션 중, Web(Spring MVC)에 집중할 수 있는 어노테이션임.
- 선언할 경우 @Controller, @ControllerAdvice등을 사용할 수 있음.
- 단, @Service, @Component, @Repository등은 사용 불가.
- 여기서는 컨트롤러만 사용하기 때문에 선언함.
Autowired
private MockMvc mvc
- 웹 API 테스트할 때 사용,
- 스프링 MVC 테스트의 시작점
- 이 클래스를 통해 HTTP GET, POST등에 대한 API테스트 할 수 있음.
RequestBuilder builder = MockMvcRequestBuilders.get("/hello");
- MockMvc를 통해 /hello로 HTTP GET요청을 함
- 체이닝이 지원되어 아래와 같이 여러 검증 기능을 이어서 선언 가능
.andExpect(content().string(hello))
- mvc.perform의 결과를 검증
- 응답 본문의 내용을 검증
- Controller 에서 "hello" 를 리턴하기 때문에 이 값이 맞는지 검증
.andExpect(status().isOk());
- HTTP Header의 Status를 검증
- 200,404,500 등의 상태를 검증
- 여기서는 OK, 즉 200 인지 아닌지를 검증
안녕하세요! 저도 같은 책을 보고 혼자서 구현해보고 있는데, 제가 개발쪽이 초짜인지라 책을 무작정 따라하면서 구글링 하고 반복하면서 하는중인데..
책에 나온대로 적어주고 test를 돌렸는데
java.lang.AssertionError: Status
필요:200
실제 :404
이런 에러가 나서요 ㅠㅠ
쓰신 블로그 글에 의하면 .andExpect(status().isOk());
여기 부분에서 문제가 생긴건데.. 혹시 해결책을 알고 계실까요??
구글링을 해봤는데, 마땅한 해결책을 찾지 못해서요 ㅠㅠㅠ
패키지의 경로도 확인해보고 해봤는데, 해결이 안됩니다... ㅠ
아 그리고 ExtendWith / RunWith는 혹시 junit 의 버전 차이인것 같던데.. 이게 문제가 되지는 않겠죠?