Backend/책,강의
[Book] 2) 테스트코드 작성
지수쓰
2020. 6. 29. 02:42
반응형
책 : 스프링부트와 AWS로 혼자 구현하는 웹서비스 (이동욱님 지음, 프리렉)
패키지, 자바클래스 추가
// Application.java
package com.project.freelec.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args){
/*
* SpringApplication.run으로 인해 내장 WAS(Web application server)실행
* 내장 WAS란 별도로 외부에 WAS를 두지 않고 애플리케이션을 실행할 때 WAS를 실행하는것을 이야기함.
* 서버에 톰캣을 설치할 필요없이 스프링 부트로 만들어진 JAR파일을 실행하면됨.(jar:실행가능한 java 패키징 파일)
*/
SpringApplication.run(Application.class,args);
}
}
@RestController
: 컨트롤러를 JSON을 반환하는 컨트롤러로 만들어줌.
package com.project.freelec.springboot.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)
@WebMvcTest(controllers = HelloController.class)
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
: 테스트를 진행할 때 SpringRunner라는 스프링 실행자를 사용한다. ( Junit에 내장된 실행자외에 다른 실행자로 실행시키는 것임. 스프링부트 테스트와 JUnit 사이에 연결자역할)
@WebMvcTeset
: 스프링테스트 어노테이션중 Web(Spring MVC)에 집중할 수 있는 어노테이션. 컨트롤러만 사용 가능
Run hello가 리턴된다를 클릭