테스트 코드 작성을 도와주는 프레임워크 : JUnit
JUnit5까지 나왔지만 아직 많은 회사에서 JUnit4를 사용하기 때문에 나도 JUnit4사용
web 패키지에 클래스를 생성해준다.
💡 갑자기 Git에 add할거냐고 해서 더 이상 묻지 않기하고 add 하였음
package com.example.project2.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController //(1) ❓
public class HelloController {
@GetMapping("/hello") //(2) ❓
public String hello(){
return "hello";
}
}
(1) @RestController
- 컨트롤러를 JSON으로 반환하는 컨트롤러로 만들어 준다.
(2) @GetMapping
- HTTP Method인 Get의 요청을 받을 수 있는 API를 만들어 준다.
- /hello로 요청이 오면 문자열 hello를 반환
src/test/java/com.example.project2에 web패키지 생성 (앞에서 생성했던 디렉토리를 test파일에도 똑같이 생성해준다.)
test파일의 web패키지에 HelloControllerTest 클래스 생성
package com.example.project2.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class) //(1) ❓
@WebMvcTest(controllers = HelloController.class) //(2) ❓
public class HelloControllerTest {
@Autowired //(3) ❓
private MockMvc mvc; //(4) ❓
@Test
public void hellotest() throws Exception{
String hello = "hello";
mvc.perform(get("/hello")) //(5) ❓
.andExpect(status().isOk()) //(6) ❓
.andExpect(content().string(hello)); //(7) ❓
}
}
(1) @RunWith(SpringRunner.class)
- 테스트를 진행할 때 JUnit에 내장된 실행자 외에 다른 실행자를 실행
- 여기서는 SpringRunner라는 스프링 실행자 사용
- 즉, 스프링부트 테스트와 JUnit 사이에 연결자 역할
(2) @WebMvcTest
- 여러 스프링테스트 어노테이션 중, Web(Spring MVC)에 집중할 수 있는 어노테이션
- 선언할 경우 @Controller, @ControllerAdvice 사용 가능
- 단, @Service, @Component @Repository 사용불가
- 여기서는 컨트롤러만 사용
(3) @Autowired
- 스프링이 관리하는 Bean을 주입 받음
(4) private MockMVC mvc
- 웹 API를 테스트 할 때 사용
- 스프링 MVC테스트의 시작점
- 이 클래스를 통해 HTTP GET, POST 등에 대한 API 테스트를 할 수 있다.
(5) mvc.perform(get("/hello"))
- MockMvc를 통해 /hello 주소로 HTTP GET요청을 한다.
- 체이닝이 지원되어 아래와 같이 여러 검증기능을 이어서 선언할 수 있다.
(6) .andExpect(status().isOk())
- mvc.perform의 결과를 검증
- HTTP Header 의 Status를 검증
- 에러 번호? 200, 404, 500 등의 상태를 검증
- 여기선 OK(200)인지 아닌지 검증
(7) .andExpect(Content().string(hello))
- mvc.perfomr의 결과를 검증
- 응답 본문의 내용을 검증
- Controller에서 "hello"를 리턴하기 때문에 이 값이 맞는지 검증
엥 테스트 코드의 리소스 파일이 없다며 에러 발생.
Main 코드는 잘실행된다.
좀 더 알아 보자..