Project/React+Java
2. SpringBoot + Controller TestCase 설정 확인
건담아빠
2022. 7. 21. 16:17
https://github.com/dchkang83/project-board
GitHub - dchkang83/project-board
Contribute to dchkang83/project-board development by creating an account on GitHub.
github.com
1. lombok 의존성 추가
# /project-board/back-end/gundam/build.gradle
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
lombok dependency 설정 후 library reload
2. SampleTests.java 작성
package com.main.gundam.sample;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Arrays;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SampleTests {
@BeforeAll
public static void beforeAll() {
log.info("########## beforeAll");
}
@BeforeEach
public void beforeEach() {
log.info("##### beforeEach");
}
@AfterEach
public void afterEach() {
log.info("##### afterEach");
}
@AfterAll
public static void afterAll() {
log.info("########## afterAll");
}
@Test
@DisplayName("기본적인 테스트 테스트")
public void test0001() {
log.info("test0001");
final int[] numbers = {-3, -5, 1, 7, 4, -2};
final int[] expected = {-5, -3, -2, 1, 4, 7};
Arrays.sort(numbers);
assertArrayEquals(expected, numbers);
}
@ParameterizedTest
@DisplayName("String parameters")
@ValueSource(strings = {
"a", "b", "d", "e", "f"
})
public void argsStringsTest(final String s) {
log.info(s);
}
// @ParameterizedTest
// @DisplayName("Ints parameters")
// @ValueSource(ints = {
// 1, 2, 3, 4, 5
// })
// public void argsInts1Test(final Integer i) {
// Assertions.assertEquals(3, i);
// }
@ParameterizedTest
@DisplayName("Ints parameters")
@ValueSource(ints = {
1, 2, 3, 4, 5
})
public void argsInts2Test(final Integer i) {
Assertions.assertTrue(convert(i));
}
private boolean convert(Integer i) {
return i < 6;
}
}
3. RestApiController.java 작성
package com.main.gundam.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;
@RestController
@RequestMapping(value = "/main", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE})
@RequiredArgsConstructor
public class RestApiController {
@GetMapping("home")
public String home() {
return "<h1>home</h1>";
}
@GetMapping("/get/{userId}")
public String get(@PathVariable(value = "userId") final String userId) {
return userId;
}
}
4. RestApiControllerTests.java 테스트 케이스 작성
package com.main.gundam.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
@Slf4j
public class RestApiControllerTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@BeforeAll
static void beforeAll() {
}
@BeforeEach
public void beforeEach() {
objectMapper = Jackson2ObjectMapperBuilder.json()
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.modules(new JavaTimeModule())
.build();
}
// 유저 조회 테스트
@Test
public void getTest() throws Exception {
String url = "/main/get/test3";
String content = "{\"name\": \"Ted\", \"hobby\": \"aa\"}";
mockMvc.perform(MockMvcRequestBuilders.get(url)
.contentType(MediaType.APPLICATION_JSON)
.content(content))
.andExpect(result -> {
MockHttpServletResponse response = result.getResponse();
// log.info(response.getContentAsString());
log.info("getContentAsString : " + response.getContentAsString());
log.info("getContentType : " + response.getContentType());
})
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.content().string("test3"))
// .andDo(MockMvcResultHandlers.print())
.andReturn()
.getResponse()
;
}
}