Created
February 28, 2024 01:41
-
-
Save msbaek/8c34a3703ce225316c9b41135bfd5e18 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @RunWith(SpringRunner.class) | |
| @SpringBootTest( | |
| properties = { | |
| "property.value=propertyTest", | |
| "value=test" | |
| }, | |
| classes = {TestApplication.class}, | |
| webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT | |
| ) | |
| public class TestApplicationTests { | |
| @Value("${value}") | |
| private String value; | |
| @Value("${property.value}") | |
| private String propertyValue; | |
| @Test | |
| public void contextLoads() { | |
| assertThat(value, is("test")); | |
| assertThat(propertyValue, is("propertyTest")); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @RunWith(SpringRunner.class) | |
| @WebMvcTest(BookApi.class) | |
| public class BookApiTest { | |
| @Autowired | |
| private MockMvc mvc; | |
| @MockBean | |
| private BookService bookService; | |
| @Test | |
| public void getBook_test() throws Exception { | |
| //given | |
| final Book book = new Book(1L, "title", 1000D); | |
| given(bookService.getBook()).willReturn(book); | |
| //when | |
| final ResultActions actions = mvc.perform(get("/books/{id}", 1L) | |
| .contentType(MediaType.APPLICATION_JSON_UTF8)) | |
| .andDo(print()); | |
| //then | |
| actions | |
| .andExpect(status().isOk()) | |
| .andExpect(jsonPath("id").value(1L)) | |
| .andExpect(jsonPath("title").value("title")) | |
| .andExpect(jsonPath("price").value(1000D)) | |
| ; | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @RunWith(SpringRunner.class) | |
| @DataJpaTest | |
| @ActiveProfiles("test") | |
| @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) | |
| public class BookJpaTest { | |
| @Autowired | |
| private BookRepository bookRepository; | |
| @Test | |
| public void book_save_test() { | |
| final Book book = new Book("title", 1000D); | |
| final Book saveBook = bookRepository.save(book); | |
| assertThat(saveBook.getId(), is(notNullValue())); | |
| } | |
| @Test | |
| public void book_save_and_find() { | |
| final Book book = new Book("title", 1000D); | |
| final Book saveBook = bookRepository.save(book); | |
| final Book findBook = bookRepository.findById(saveBook.getId()).get(); | |
| assertThat(findBook.getId(), is(notNullValue())); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @RunWith(SpringRunner.class) | |
| @RestClientTest(BookRestService.class) | |
| public class BookRestServiceTest { | |
| @Rule | |
| public ExpectedException thrown = ExpectedException.none(); | |
| @Autowired | |
| private BookRestService bookRestService; | |
| @Autowired | |
| private MockRestServiceServer server; | |
| @Test | |
| public void rest_test() { | |
| server.expect(requestTo("/rest/test")) | |
| .andRespond( | |
| withSuccess(new ClassPathResource("/test.json", getClass()), MediaType.APPLICATION_JSON)); | |
| Book book = bookRestService.getRestBook(); | |
| assertThat(book.getId(), is(notNullValue())); | |
| assertThat(book.getTitle(), is("title")); | |
| assertThat(book.getPrice(), is(1000D)); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @RunWith(SpringRunner.class) | |
| @JsonTest | |
| public class BookJsonTest { | |
| @Autowired | |
| private JacksonTester<Book> json; | |
| @Test | |
| public void json_test() throws IOException { | |
| final Book book = new Book("title", 1000D); | |
| String content= "{\n" + | |
| " \"id\": 0,\n" + | |
| " \"title\": \"title\",\n" + | |
| " \"price\": 1000\n" + | |
| "}"; | |
| assertThat(json.parseObject(content).getTitle()).isEqualTo(book.getTitle()); | |
| assertThat(json.write(book)).isEqualToJson("/test.json"); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| https://rieckpil.de/spring-boot-test-slices-overview-and-usage/ | |
| //--- | |
| @WebMvcTest(ShoppingCartController.class) | |
| class ShoppingCartControllerTest { | |
| @Autowired | |
| private MockMvc mockMvc; | |
| @MockBean | |
| private ShoppingCartRepository shoppingCartRepository; | |
| @Test | |
| public void shouldReturnAllShoppingCarts() throws Exception { | |
| when(shoppingCartRepository.findAll()).thenReturn( | |
| List.of(new ShoppingCart("42", | |
| List.of(new ShoppingCartItem( | |
| new Item("MacBook", 999.9), 2) | |
| )))); | |
| this.mockMvc.perform(get("/api/carts")) | |
| .andExpect(status().isOk()) | |
| .andExpect(jsonPath("$[0].id", Matchers.is("42"))) | |
| .andExpect(jsonPath("$[0].cartItems.length()", Matchers.is(1))) | |
| .andExpect(jsonPath("$[0].cartItems[0].item.name", Matchers.is("MacBook"))) | |
| .andExpect(jsonPath("$[0].cartItems[0].quantity", Matchers.is(2))); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @DataJpaTest | |
| class BookRepositoryTest { | |
| @Autowired | |
| private DataSource dataSource; | |
| @Autowired | |
| private EntityManager entityManager; | |
| @Autowired | |
| private BookRepository bookRepository; | |
| @Test | |
| public void testCustomNativeQuery() { | |
| assertEquals(1, bookRepository.findAll().size()); | |
| assertNotNull(dataSource); | |
| assertNotNull(entityManager); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @JdbcTest | |
| public class JdbcAccessTest { | |
| @Autowired | |
| private DataSource dataSource; | |
| @Autowired | |
| private JdbcTemplate jdbcTemplate; | |
| @Test | |
| public void shouldReturnBooks() { | |
| assertNotNull(dataSource); | |
| assertNotNull(jdbcTemplate); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| <dependency> | |
| <groupId>de.flapdoodle.embed</groupId> | |
| <artifactId>de.flapdoodle.embed.mongo</artifactId> | |
| <scope>test</scope> | |
| </dependency> | |
| @DataMongoTest | |
| class ShoppingCartRepositoryTest { | |
| @Autowired | |
| private MongoTemplate mongoTemplate; | |
| @Autowired | |
| private ShoppingCartRepository shoppingCartRepository; | |
| @Test | |
| public void shouldCreateContext() { | |
| shoppingCartRepository.save(new ShoppingCart("42", | |
| List.of(new ShoppingCartItem( | |
| new Item("MacBook", 999.9), 2) | |
| ))); | |
| assertNotNull(mongoTemplate); | |
| assertNotNull(shoppingCartRepository); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| public class PaymentResponse { | |
| @JsonIgnore | |
| private String id; | |
| private UUID paymentConfirmationCode; | |
| @JsonProperty("payment_amount") | |
| private BigDecimal amount; | |
| @JsonFormat( | |
| shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd|HH:mm:ss", locale = "en_US") | |
| private LocalDateTime paymentTime; | |
| } | |
| @JsonTest | |
| class PaymentResponseTest { | |
| @Autowired | |
| private JacksonTester<PaymentResponse> jacksonTester; | |
| @Autowired | |
| private ObjectMapper objectMapper; | |
| @Test | |
| public void shouldSerializeObject() throws IOException { | |
| assertNotNull(objectMapper); | |
| PaymentResponse paymentResponse = new PaymentResponse(); | |
| paymentResponse.setId("42"); | |
| paymentResponse.setAmount(new BigDecimal("42.50")); | |
| paymentResponse.setPaymentConfirmationCode(UUID.randomUUID()); | |
| paymentResponse.setPaymentTime(LocalDateTime.parse("2020-07-20T19:00:00.123")); | |
| JsonContent<PaymentResponse> result = jacksonTester.write(paymentResponse); | |
| assertThat(result).hasJsonPathStringValue("$.paymentConfirmationCode"); | |
| assertThat(result).extractingJsonPathNumberValue("$.payment_amount").isEqualTo(42.50); | |
| assertThat(result).extractingJsonPathStringValue("$.paymentTime").isEqualTo("2020-07-20|19:00:00"); | |
| assertThat(result).doesNotHaveJsonPath("$.id"); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @RestClientTest(RandomQuoteClient.class) | |
| class RandomQuoteClientTest { | |
| @Autowired | |
| private RandomQuoteClient randomQuoteClient; | |
| @Autowired | |
| private MockRestServiceServer mockRestServiceServer; | |
| @Test | |
| public void shouldReturnQuoteFromRemoteSystem() { | |
| String response = "{" + | |
| "\"contents\": {"+ | |
| "\"quotes\": ["+ | |
| "{"+ | |
| "\"author\": \"duke\"," + | |
| "\"quote\": \"Lorem ipsum\""+ | |
| "}"+ | |
| "]"+ | |
| "}" + | |
| "}"; | |
| this.mockRestServiceServer | |
| .expect(MockRestRequestMatchers.requestTo("/qod")) | |
| .andRespond(MockRestResponseCreators.withSuccess(response, MediaType.APPLICATION_JSON)); | |
| String result = randomQuoteClient.getRandomQuote(); | |
| assertEquals("Lorem ipsum", result); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| //////////////////////////////////////////////////////////////// | |
| //////////////////////////////////////////////////////////////// | |
| //////////////////////////////////////////////////////////////// | |
| //////////////////////////////////////////////////////////////// | |
| @SpringBootTest | |
| @AutoConfigureMockMvc | |
| //@Sql("classpath:init.sql") | |
| public class MemberApiIntegrationTest { | |
| @Autowired private MockMvc mockMvc; | |
| @Autowired private ObjectMapper objectMapper; | |
| @Autowired private MemberRepository memberRepository; | |
| @DisplayName("대기 상태 회원을 승인하면 회원 상태가 ACTIVE로 바뀜") | |
| @Test | |
| void confirmMember() throws Exception { | |
| memberRepository.save(Member.create("id", MemberStatus.WAITING)); | |
| Member expectedResponse = Member.create("id", MemberStatus.ACTIVE); | |
| ResultActions actions = mockMvc.perform(MockMvcRequestBuilders.put("/members/{id}/confirm", "id")); | |
| actions | |
| .andExpect(status().isOk()) | |
| .andExpect(content().json(objectMapper.writeValueAsString(expectedResponse))); | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @ExtendWith(MockitoExtension.class) | |
| public class MemberApiMockMvcStandAloneModeTest { | |
| private MockMvc mockMvc; | |
| @Mock private ConfirmMemberService confirmMemberService; | |
| @InjectMocks private MemberApi memberApi; | |
| private ObjectMapper objectMapper = new ObjectMapper(); | |
| @BeforeEach | |
| void setUp() { | |
| WebApplicationContext context; | |
| mockMvc = MockMvcBuilders.standaloneSetup(memberApi) | |
| // .setControllerAdvice() | |
| // .addFilter() | |
| .build(); | |
| } | |
| @DisplayName("대기 상태 회원을 승인하면 회원 상태가 ACTIVE로 바뀜") | |
| @Test | |
| void confirmMember() throws Exception { | |
| Mockito.when(confirmMemberService.confirm("id")).thenReturn(Member.create("id", MemberStatus.ACTIVE)); | |
| Member expectedResponse = Member.create("id", MemberStatus.ACTIVE); | |
| // 실행 | |
| MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.put("/members/{id}/confirm", "id")) | |
| .andReturn().getResponse(); | |
| // 결과 | |
| assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); | |
| assertThat(response.getContentAsString()).isEqualTo( | |
| objectMapper.writeValueAsString(expectedResponse) | |
| ); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @WebMvcTest(MemberApi.class) | |
| public class MemberApiMockMvcWithWebApplicationContextTest { | |
| @Autowired private MockMvc mockMvc; | |
| @MockBean private ConfirmMemberService confirmMemberService; | |
| @Autowired private ObjectMapper objectMapper; | |
| @DisplayName("대기 상태 회원을 승인하면 회원 상태가 ACTIVE로 바뀜") | |
| @Test | |
| void confirmMember() throws Exception { | |
| Mockito.when(confirmMemberService.confirm("id")).thenReturn(Member.create("id", MemberStatus.ACTIVE)); | |
| Member expectedResponse = Member.create("id", MemberStatus.ACTIVE); | |
| // 실행 | |
| MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.put("/members/{id}/confirm", "id")) | |
| .andReturn().getResponse(); | |
| // 결과 | |
| assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); | |
| assertThat(response.getContentAsString()).isEqualTo( | |
| objectMapper.writeValueAsString(expectedResponse) | |
| ); | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////// | |
| @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) | |
| public class MemberApiSpringBootTestWithMockWebEnvironmentTest { | |
| @Autowired private TestRestTemplate restTemplate; | |
| @MockBean private ConfirmMemberService confirmMemberService; | |
| @Autowired private ObjectMapper objectMapper; | |
| @DisplayName("대기 상태 회원을 승인하면 회원 상태가 ACTIVE로 바뀜") | |
| @Test | |
| void confirmMember() throws Exception { | |
| Mockito.when(confirmMemberService.confirm("id")).thenReturn(Member.create("id", MemberStatus.ACTIVE)); | |
| Member expectedResponse = Member.create("id", MemberStatus.ACTIVE); | |
| // 실행 | |
| ResponseEntity<Member> response = restTemplate.exchange("/members/id/confirm", HttpMethod.PUT, null, Member.class); | |
| // 결과 | |
| assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); | |
| assertThat(response.getBody().getId()).isEqualTo(expectedResponse.getId()); | |
| assertThat(response.getBody().getMemberStatus()).isEqualTo(expectedResponse.getMemberStatus()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment