오답노트
[Spring] 코드 Test하기 본문
JUnit
JUnit은 Java 소스를 모듈 단위로 테스트할 수 있는 도구다.
이는 스프링 환경에 이미 Import 되어 있으며 API도 테스트 할 수 있다.
실습
import com.example.springcalculator.component.Calculator;
import com.example.springcalculator.component.DollarCalc;
import com.example.springcalculator.component.MarketApi;
import com.example.springcalculator.dto.Req;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@WebMvcTest(CalcControllerApi.class)
@AutoConfigureWebMvc
@Import({Calculator.class, DollarCalc.class})
public class CalcApiContorllerTest {
@MockBean
private MarketApi marketApi;
@Autowired
private MockMvc mockMvc;
@BeforeEach
public void init(){
Mockito.when(marketApi.connect()).thenReturn(300);
}
@Test
public void sumTest() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("http://localhost:8080/api/sum")
.queryParam("x","10")
.queryParam("y","10")
).andExpect(
MockMvcResultMatchers.status().isOk()
).andExpect(
MockMvcResultMatchers.content().string("6000")
).andDo(MockMvcResultHandlers.print());
}
@Test
public void minusTest() throws Exception {
Req req = new Req();
req.setX(10);
req.setY(10);
String json = new ObjectMapper().writeValueAsString(req);
mockMvc.perform(
MockMvcRequestBuilders.post("http://localhost:8080/api/minus")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
).andExpect(
MockMvcResultMatchers.status().isOk()
).andExpect(
MockMvcResultMatchers.jsonPath("$.result").value("0")
)
.andExpect(
MockMvcResultMatchers.jsonPath("$.response.resultCode").value("Ok")
)
.andDo(MockMvcResultHandlers.print());
}
}
'Java > Spring' 카테고리의 다른 글
[Spring JPA] Auditing (0) | 2023.07.19 |
---|---|
[Spring JPA] H2 In-Memory DB (0) | 2023.07.18 |
[Spring] Server to Server 예제 (네이버 API) (0) | 2023.07.14 |
[Spring] Server to Server (0) | 2023.07.14 |
[Spring] 비동기 처리 (Async) (0) | 2023.07.14 |