단순 API를 테스트하는것은 문제가 될 것이 없다.
하지만, Spring-boot Application의 테스트를 위해서는 새로운 방식이 도입되어야 한다.
공부를 위해 이번 포스팅에서 이것을 정리한다. (계속 업데이트하여 정리)
2020.06.21 HelloControllerTest.java
package com.tistory.cafecoder.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.*;
import static org.hamcrest.CoreMatchers.is;
@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));
}
@Test
public void helloDto가_리턴된다() throws Exception {
String name = "hello";
int amount = 1000;
mvc.perform(
get("/hello/dto")
.param("name", name)
.param("amount", String.valueOf(amount))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is(name)))
.andExpect(jsonPath("$.amount", is(amount)));
}
}
인증된 모의 사용자를 만들어서 사용한다.
권한을 추가로 지정할 수 있다.
이 어노테이션으로 인해 특정 권한을 가진 사용자가 API를 요청하는 것 과 동일한 효과를 갖게 된다.
@WebMvcTest에서 CustomOAuth2UserService을 찾을 수 없음 (0) | 2020.06.29 |
---|---|
Spring-security 모듈 추가 후 테스트 에러 해결 (0) | 2020.06.29 |
신규 모듈 추가시 전체 테스트 에러가 발생한다. (0) | 2020.06.29 |
Spring-boot HTML Test (0) | 2020.06.24 |
단위 테스트 소개 (0) | 2020.06.18 |