
//HelloController.java
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
@RestController : 컨트롤러를 JSON을 반환하는 컨트롤러로 만들어 줌@GetMapping : Get 요청을 받을 수 있는 API 생성//HelloControllerTest.java
@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.class) : 테스트를 진행할 때 JUnit에 내장된 실행자 외에 다른 실행자를 실행
@WebMvcTest : Web(Spring MVC)에 집중할 수 있는 어노테이션
@Controller,@ControllerAdvice 등을 사용@Service, @Component, @Repository 등은 사용할 수 없음@Autowired : 스프링이 관리하는 빈(Bean)을 주입받음
privat MockMvc mvc
mvc.perform(get("/hello")) : MockMvc를 통해 /hello 주소로 HTTP GET 요청
.andExpect(status().isOk())
andExpect(content().string(hello))
이동욱, 스프링 부트와 AWS로 혼자 구현하는 웹 서비스