|
| 1 | +package com.baeldung.springboothsqldb.application.tests; |
| 2 | + |
| 3 | +import com.baeldung.springboothsqldb.application.entities.Customer; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.fasterxml.jackson.databind.ObjectWriter; |
| 6 | +import com.fasterxml.jackson.databind.SerializationFeature; |
| 7 | +import java.nio.charset.Charset; |
| 8 | +import org.junit.Before; |
| 9 | +import org.junit.Test; |
| 10 | +import org.junit.runner.RunWith; |
| 11 | +import org.springframework.beans.factory.annotation.Autowired; |
| 12 | +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; |
| 13 | +import org.springframework.boot.test.context.SpringBootTest; |
| 14 | +import org.springframework.http.MediaType; |
| 15 | +import org.springframework.test.context.junit4.SpringRunner; |
| 16 | +import org.springframework.test.web.servlet.MockMvc; |
| 17 | +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; |
| 18 | +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; |
| 19 | + |
| 20 | +@RunWith(SpringRunner.class) |
| 21 | +@SpringBootTest |
| 22 | +@AutoConfigureMockMvc |
| 23 | +public class CustomerControllerUnitTest { |
| 24 | + |
| 25 | + private static MediaType MEDIA_TYPE_JSON; |
| 26 | + |
| 27 | + @Autowired |
| 28 | + private MockMvc mockMvc; |
| 29 | + |
| 30 | + @Before |
| 31 | + public void setUpJsonMediaType() { |
| 32 | + MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); |
| 33 | + |
| 34 | + } |
| 35 | + |
| 36 | + @Test |
| 37 | + public void whenPostHttpRequesttoCustomers_thenStatusOK() throws Exception { |
| 38 | + Customer customer = new Customer("John", "john@domain.com"); |
| 39 | + ObjectMapper mapper = new ObjectMapper(); |
| 40 | + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); |
| 41 | + ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); |
| 42 | + String requestJson = objectWriter.writeValueAsString(customer); |
| 43 | + |
| 44 | + this.mockMvc |
| 45 | + .perform(MockMvcRequestBuilders.post("/customers") |
| 46 | + .contentType(MEDIA_TYPE_JSON) |
| 47 | + .content(requestJson) |
| 48 | + ) |
| 49 | + |
| 50 | + .andExpect(MockMvcResultMatchers.status().isOk()); |
| 51 | + } |
| 52 | + |
| 53 | + @Test |
| 54 | + public void whenGetHttpRequesttoCustomers_thenStatusOK() throws Exception { |
| 55 | + this.mockMvc |
| 56 | + .perform(MockMvcRequestBuilders.get("/customers")) |
| 57 | + |
| 58 | + .andExpect(MockMvcResultMatchers.content().contentType(MEDIA_TYPE_JSON)) |
| 59 | + .andExpect(MockMvcResultMatchers.status().isOk()); |
| 60 | + } |
| 61 | +} |
0 commit comments