내가 직접 손으로 타이핑 안해보면 집중이 안돼서 쓰는 이것저것 모음집 ^ ^ . .
Mocking이란?
참조
테스트를 위해 실제 객체를 사용하는 것처럼 테스트를 위해 만든 모형!!
// 프로퍼티를 key=value 형태로 직접 추가 가능
@SpringBootTest(properties = {"name=minju"}
public class ExSpringBootTest {
@Value("${name}")
private STring name;
...
}
}
// src/test/test.yml에 값을 정의해놓고 긁어올 수도 있음
@SpringBootTest(properties = {"spring.config.location = classpath:test.yml"})
public class ExSpringBootTest {
@Value("{minju.age}")
private int age;
...
}
}
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class ExControllerTest_Mock {
@Autowired
MockMvc mockMvc;
@Test
public void exTest() throws Excpetion {
mockMvc.performt(get("/"))
.andExpect(status().isOk())
.andExpect(content().string("Hello"));
}
}
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class exTestController_Random_port {
@Autowired
TestRestTemplate testRestTemplate;
@MockBean
ExService exService;
@Test
public void exTest() throws Exception {
when(exService.getName()).thenReturn("~~");
String result = testResetTemplate.getForObjcet("/", String.class);
Assertions.assertThat(result).isEqualTo("hello");
}
}
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class test_WebTestCleint {
@Autowired
WebTestClient webTestClient;
@MockBean
TestMockService testMockService;
@Test
public void testMethod() throws Exception {
when(testMockService.getName()).thenReturn("~~");
webClientTest.get().uri("/").exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("hello");
}
}
WebTestClient와 RestTemplate 비교
- WebTestClient는 spring5부터 지원한다.
- RestTemplate은 3부터 지원한다.
- WebTestClient는 NonBlock + Async
- RestTemplate은 Sync
종류는!
직렬화/역직렬화 대상이 되는 클래스 정의
@JsonNaming(PropertyNamingStrategies.LowerCaseStrategy.class)
@Getter
@Setter
@AllArgsConstructor
public class UserDetails {
private Long id;
private String firstName;
private String lastName;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy.MM.dd")
private LocalDate dateOfBirth;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private boolean enabled;
}
@JsonTest를 사용하여 직렬화, 역직렬화와 관련된 테스트 코드 추가
@JsonTest
public class SampleControllerJsonTest {
@Autowired
private JacksonTester<UserDetails> json;
@Test
public void testSerialize() throws IOException {
UserDetails userDetails = new UserDetails(1L, "Duke", "Java", LocalDate.of(1999.3.8), true);
JsonContent<UserDetails> result = this.json.write(userDetails);
assertThat(result).hasJsonPathStringValue("$.firstname");
assertThat(result).extractingJsonPathStringValue("$.firstname).isEqualTo("Duke"0;
assertThat(result).extractingJsonPathStringValue("$.lastname").isEqualTo("Java");
assertThat(result).extractingJsonPathStringValue("$.dateofbirth").isEqualTo("1999.03.08"0;
}
@Test
public void testDeserialize() throws IOException {
String jsonContent = "{\\"firstname\\":\\"Mike\\", \\"lastname\\": \\"Meyer\\"," +
" \\"dateofbirth\\":\\"1990.05.15\\"," +
" \\"id\\": 42, \\"enabled\\": true}";
UserDetails result = this.json.parse(jsonContent).getObject();
assertThat(result.getFirstName()).isEqualTo("Mike");
...
assertThat(result.getDateOfBirth()).isEqualTo(LocalDate.of(1990, 05,15));
}
}
@WebMvcTest(SampleController.class) // 컨트롤러만 빈으로 등록함
public class SampleControllerWebMvcTest {
@MockBean
SampleService mockSampleService; // 필요한 빈은 mock bean으로
@Autowired
MockMvc mockMvc;
@Test
public void testHell() throws Exception {
when(mockSampleservice.getName()).thenReturn("minju");
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("hello minjU"))
.andDo(print());
}
}
Spring WebFlux : 스프링 5에서 새로 등장한 웹 어플리케이션에서 리액티브 프로그래밍을 제공하는 프레임워크
@WebFluxTest(SampleController.class)
public class SampleControllerWebFluxTest {
@MockBean
SampleService mockSampleService;
@Autowired
WebTestClient webTestClient;
@Test
public void testHeelo() {
when(mockSampleService.getName()).thenReturn("minjU");
webTestClient.get().uri("/hello")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("hello minjU");
}
}