* 테스트 코드의 작성이유?
- 개발단계 초기에 문제 발견
- 테스트 코드가 있다면 코드 수정시에 WAS를 계속 올렸다 내렸다 하면서 직접 검증하지 않아도 된다.
등 등..
1. Package, Java Class 생성
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication 어노테이션이 있는 Application.java가 프로젝트의 시작지점(main)이 된다.
해당 어노테이션은 기본적인 스프링부트의 설정들을 선언한다.
스프링부트는 시작지점부터 읽어내려가기 때문에 Application class가 가장 최상단에 있어야한다.
run() 메소드를 통해 내장 WAS를 사용하여 서버를 실행한다.
* 내장WAS를 권장하는 이유?
- 외장과 내장WAS는 큰 차이는 없으나 외장WAS를 사용하게되면 모든 서버는 WAS의 버전,종류,설정을 일치시켜야 한다.
itnovice1.blogspot.com/2019/01/jar-war.html
2. 컨트롤러 생성
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을 반환하는 컨트롤러로 명시
@GetMapping(xxx) - xxx로 들어온 HTTP Get 메소드를 받아주는 API 명시
3. 테스트 코드 작성
src/main이 아닌 src/test의 위치에 위의 패키지,class를 그대로 복붙.
클래스명만 xxxTest.java로 변경
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)
@WebMvcTest
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void hello_리턴검증하기() throws Exception {
String hello = "hello";
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string(hello));
}
}
@RunWith - 테스트 진행시 실행시킬 실행자를 괄호에 넣음. 안넣으면 JUnit 실행자로 지정됨. 여기선 SpringRunner실행자이다.
@WebMvcTest - Web에만 집중할 수 있는 어노테이션. (@Service, @Component, @Repository등 사용불가능)
MockMvc에 관한 설정을 자동으로 수행해주는 어노테이션입니다. @WebMvcTest 어노테이션을 사용하면 테스트에 사용할
@Controller클래스와 @ControllerAdvice, @JsonComponent, @Filter, WebMvcConfigurer, HandlerMethodArgumentResolver 등을 스캔한다. 그리고 MockMvc를 자동으로 설정하여 빈으로 등록합니다.
MockMvc ?
웹 API 테스트 할 때 사용하는 객체.. HTTP GET,POST등의 API테스트가 가능하다.
실제 객체와 비슷하지만 테스트에 필요한 기능만 가지는 가짜 객체를 만들어서 애플리케이션 서버에 배포하지 않고도 스프링 MVC 동작을 재현할 수 있는 클래스를 의미합니다.
.andExpect(status().isOk()) - MockMvc 객체의 결과 검증 : 200,404,500과 같은 서버status확인 ( Ok == 200 )
.andExpect(content().string(hello)) - MockMvc 객체의 결과 검증: 응답 본문 내용 검증 ( hello가 return 됐는지 비교 )
4. 테스트 실행
화살표를 통해 테스트 검증
콘솔에 위와같이 passed가 나오면 테스트 통과다.
5. 실제 페이지에서 테스트 수동 실행
src/main/java의 Application.java를 실행한뒤 로그에 찍힌 port 8080대로 http://localhost:8080/hello로 접속하면 hello가 나오는 것을 확인할 수 있다.
2021-01-05 21:57:42.293 INFO 15836 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
출처 - 스프링 부트와 AWS로 혼자 구현하는 웹서비스
'프로그래밍 > Spring Boot FW' 카테고리의 다른 글
[SpringBoot] 게시판 만들기(4) - 게시글 수정, 삭제 VIEW/API만들기 - REST API (0) | 2021.01.17 |
---|---|
[SpringBoot] 게시판 만들기(3) - 게시글 등록,조회 VIEW/API만들기 (0) | 2021.01.17 |
[SpringBoot] 게시판 만들기(2) - 템플릿 엔진을 이용하여 화면 구성하기 (0) | 2021.01.13 |
[SpringBoot] 게시판 만들기(1) - 스프링 부트와 JPA 연동으로 DB 다루기 (0) | 2021.01.10 |
[SpringBoot] @어노테이션 정리 (0) | 2021.01.05 |