JAVA-3534: Move spring-rest-http into spring-web-modules
This commit is contained in:
+82
@@ -0,0 +1,82 @@
|
||||
|
||||
package com.baeldung.requestmapping;
|
||||
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.baeldung.config.MvcConfig;
|
||||
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = MvcConfig.class)
|
||||
@WebAppConfiguration
|
||||
@AutoConfigureWebClient
|
||||
public class BazzNewMappingsExampleIntegrationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingAllBazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(get("/bazz"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$", hasSize(4)))
|
||||
.andExpect(jsonPath("$[1].id", is("2")))
|
||||
.andExpect(jsonPath("$[1].name", is("Bazz2")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(get("/bazz/1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("1")))
|
||||
.andExpect(jsonPath("$.name", is("Bazz1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(post("/bazz").param("name", "Bazz5"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("5")))
|
||||
.andExpect(jsonPath("$.name", is("Bazz5")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpdatingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(put("/bazz/5").param("name", "Bazz6"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("5")))
|
||||
.andExpect(jsonPath("$.name", is("Bazz6")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeletingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(delete("/bazz/5"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("5")));
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.requestmapping;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebMvcTest(FooMappingExamplesController.class)
|
||||
public class FooMappingExamplesControllerUnitTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
@Test
|
||||
public void givenAcceptsJson_whenGetDuplicate_thenJsonResponseReturned() throws Exception {
|
||||
mvc.perform(get("/ex/foos/duplicate")
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("{\"message\":\"Duplicate\"}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAcceptsXml_whenGetDuplicate_thenXmlResponseReturned() throws Exception {
|
||||
mvc.perform(get("/ex/foos/duplicate")
|
||||
.accept(MediaType.APPLICATION_XML))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("<message>Duplicate</message>"));
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package com.baeldung.responseheaders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
public class ResponseHeaderLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8082/spring-rest";
|
||||
private static final String SINGLE_BASE_URL = BASE_URL + "/single-response-header";
|
||||
private static final String FILTER_BASE_URL = BASE_URL + "/filter-response-header";
|
||||
private static final String SERVICE_SINGLE_RESPONSE_HEADER = "Baeldung-Example-Header";
|
||||
private static final String SERVICE_FILTER_RESPONSE_HEADER = "Baeldung-Example-Filter-Header";
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate template;
|
||||
|
||||
@Test
|
||||
public void whenHttpServletResponseRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/http-servlet-response";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-HttpServletResponse"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResponseEntityConstructorRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/response-entity-constructor";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityContructor"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResponseEntityConstructorAndMultipleHeadersRequest_thenObtainResponseWithCorrectHeaders() {
|
||||
final String requestUrl = "/response-entity-contructor-multiple-headers";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityConstructorAndHeaders"));
|
||||
assertThat(responseHeaders).containsEntry("Accept", Arrays.asList(MediaType.APPLICATION_JSON.toString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResponseEntityBuilderRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/response-entity-builder";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilder"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResponseEntityBuilderAndHttpHeadersRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/response-entity-builder-with-http-headers";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilderWithHttpHeaders"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterWithNoExtraHeaderRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/no-extra-header";
|
||||
ResponseEntity<String> response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterWithExtraHeaderRequest_thenObtainResponseWithCorrectHeaders() {
|
||||
final String requestUrl = "/extra-header";
|
||||
ResponseEntity<String> response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter"));
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ExtraHeader"));
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.service.impl;
|
||||
|
||||
import com.baeldung.service.CustomerIdGenerator;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class CustomerIdGeneratorImplUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIdGeneratedPreviously_whenGenerated_thenIdIsIncremented(){
|
||||
CustomerIdGenerator customerIdGenerator = new CustomerIdGeneratorImpl();
|
||||
int firstId = customerIdGenerator.generateNextId();
|
||||
assertThat(customerIdGenerator.generateNextId()).isEqualTo(++firstId);
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.baeldung.service.impl;
|
||||
|
||||
|
||||
import com.baeldung.model.Customer;
|
||||
import com.baeldung.service.CustomerIdGenerator;
|
||||
import com.baeldung.service.CustomerService;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
import static com.baeldung.model.Customer.fromCustomer;
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Optional.empty;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CustomerServiceImplUnitTest {
|
||||
|
||||
@Mock
|
||||
private CustomerIdGenerator mockCustomerIdGenerator;
|
||||
|
||||
private CustomerService customerService;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
customerService = new CustomerServiceImpl(mockCustomerIdGenerator);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomerIsCreated_thenNewCustomerDetailsAreCorrect() {
|
||||
Map<String, Boolean> communicationPreferences = new HashMap<>();
|
||||
communicationPreferences.put("post", true);
|
||||
communicationPreferences.put("email", true);
|
||||
Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences);
|
||||
given(mockCustomerIdGenerator.generateNextId()).willReturn(1);
|
||||
|
||||
Customer newCustomer = customerService.createCustomer(customer);
|
||||
|
||||
assertThat(newCustomer.getId()).isEqualTo("1");
|
||||
assertThat(newCustomer.getTelephone()).isEqualTo("001-555-1234");
|
||||
assertThat(newCustomer.getFavorites()).containsExactly("Milk", "Eggs");
|
||||
assertThat(newCustomer.getCommunicationPreferences()).isEqualTo(communicationPreferences);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonExistentCustomer_whenCustomerIsLookedUp_thenCustomerCanNotBeFound() {
|
||||
assertThat(customerService.findCustomer("CUST12345")).isEqualTo(empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomerIsCreated_thenCustomerCanBeFound() {
|
||||
Map<String, Boolean> communicationPreferences = new HashMap<>();
|
||||
communicationPreferences.put("post", true);
|
||||
communicationPreferences.put("email", true);
|
||||
Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences);
|
||||
given(mockCustomerIdGenerator.generateNextId()).willReturn(7890);
|
||||
|
||||
customerService.createCustomer(customer);
|
||||
Customer lookedUpCustomer = customerService.findCustomer("7890").get();
|
||||
|
||||
assertThat(lookedUpCustomer.getId()).isEqualTo("7890");
|
||||
assertThat(lookedUpCustomer.getTelephone()).isEqualTo("001-555-1234");
|
||||
assertThat(lookedUpCustomer.getFavorites()).containsExactly("Milk", "Eggs");
|
||||
assertThat(lookedUpCustomer.getCommunicationPreferences()).isEqualTo(communicationPreferences);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomerUpdated_thenDetailsUpdatedCorrectly() {
|
||||
given(mockCustomerIdGenerator.generateNextId()).willReturn(7890);
|
||||
Map<String, Boolean> communicationPreferences = new HashMap<>();
|
||||
communicationPreferences.put("post", true);
|
||||
communicationPreferences.put("email", true);
|
||||
Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences);
|
||||
Customer newCustomer = customerService.createCustomer(customer);
|
||||
|
||||
Customer customerWithUpdates = fromCustomer(newCustomer);
|
||||
customerWithUpdates.setTelephone("001-555-6789");
|
||||
customerService.updateCustomer(customerWithUpdates);
|
||||
Customer lookedUpCustomer = customerService.findCustomer("7890").get();
|
||||
|
||||
assertThat(lookedUpCustomer.getId()).isEqualTo("7890");
|
||||
assertThat(lookedUpCustomer.getTelephone()).isEqualTo("001-555-6789");
|
||||
assertThat(lookedUpCustomer.getFavorites()).containsExactly("Milk", "Eggs");
|
||||
assertThat(lookedUpCustomer.getCommunicationPreferences()).isEqualTo(communicationPreferences);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.uribuilder;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
public class SpringUriBuilderIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void constructUri() {
|
||||
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/junit-5").build();
|
||||
|
||||
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructUriEncoded() {
|
||||
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/junit 5").build().encode();
|
||||
|
||||
assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructUriFromTemplate() {
|
||||
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/{article-name}").buildAndExpand("junit-5");
|
||||
|
||||
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructUriWithQueryParameter() {
|
||||
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.google.com").path("/").query("q={keyword}").buildAndExpand("baeldung");
|
||||
|
||||
assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void expandWithRegexVar() {
|
||||
String template = "/myurl/{name:[a-z]{1,5}}/show";
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build();
|
||||
uriComponents = uriComponents.expand(Collections.singletonMap("name", "test"));
|
||||
|
||||
assertEquals("/myurl/test/show", uriComponents.getPath());
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.web.controller.customer;
|
||||
|
||||
import com.baeldung.model.Customer;
|
||||
import com.baeldung.service.CustomerService;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static java.util.Collections.emptyList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public class CustomerRestControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private CustomerService customerService;
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate testRestTemplate;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
testRestTemplate.getRestTemplate().setRequestFactory(new HttpComponentsClientHttpRequestFactory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingCustomer_whenPatched_thenOnlyPatchedFieldsUpdated() {
|
||||
Map<String, Boolean> communicationPreferences = new HashMap<>();
|
||||
communicationPreferences.put("post", true);
|
||||
communicationPreferences.put("email", true);
|
||||
Customer newCustomer = new Customer("001-555-1234", Arrays.asList("Milk", "Eggs"),
|
||||
communicationPreferences);
|
||||
Customer customer = customerService.createCustomer(newCustomer);
|
||||
|
||||
|
||||
String patchBody = "[ { \"op\": \"replace\", \"path\": \"/telephone\", \"value\": \"001-555-5678\" },\n"
|
||||
+ "{\"op\": \"add\", \"path\": \"/favorites/0\", \"value\": \"Bread\" }]";
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.valueOf("application/json-patch+json"));
|
||||
ResponseEntity<Customer> patchResponse
|
||||
= testRestTemplate.exchange("/customers/{id}",
|
||||
HttpMethod.PATCH,
|
||||
new HttpEntity<>(patchBody, headers),
|
||||
Customer.class,
|
||||
customer.getId());
|
||||
|
||||
Customer customerPatched = patchResponse.getBody();
|
||||
assertThat(patchResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(customerPatched.getId()).isEqualTo(customer.getId());
|
||||
assertThat(customerPatched.getTelephone()).isEqualTo("001-555-5678");
|
||||
assertThat(customerPatched.getCommunicationPreferences().get("post")).isTrue();
|
||||
assertThat(customerPatched.getCommunicationPreferences().get("email")).isTrue();
|
||||
assertThat(customerPatched.getFavorites()).containsExactly("Bread", "Milk", "Eggs");
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.baeldung.web.controller.customer;
|
||||
|
||||
import com.baeldung.model.Customer;
|
||||
import com.baeldung.service.CustomerService;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
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.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Optional.empty;
|
||||
import static java.util.Optional.of;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
|
||||
import static org.springframework.http.MediaType.APPLICATION_JSON;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@AutoConfigureMockMvc
|
||||
public class CustomerRestControllerUnitTest {
|
||||
|
||||
private static final String APPLICATION_JSON_PATCH_JSON = "application/json-patch+json";
|
||||
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
@MockBean
|
||||
private CustomerService mockCustomerService;
|
||||
|
||||
@Autowired
|
||||
ApplicationContext context;
|
||||
|
||||
@Test
|
||||
public void whenCustomerCreated_then201ReturnedWithNewCustomerLocation() throws Exception {
|
||||
Map<String, Boolean> communicationPreferences = new HashMap<>();
|
||||
communicationPreferences.put("post", true);
|
||||
communicationPreferences.put("email", true);
|
||||
Customer customer = new Customer("001-555-1234", asList("Milk", "Eggs"), communicationPreferences);
|
||||
|
||||
Customer persistedCustomer = Customer.fromCustomer(customer);
|
||||
persistedCustomer.setId("1");
|
||||
|
||||
given(mockCustomerService.createCustomer(customer)).willReturn(persistedCustomer);
|
||||
|
||||
String createCustomerRequestBody = "{"
|
||||
+ "\"telephone\": \"001-555-1234\",\n"
|
||||
+ "\"favorites\": [\"Milk\", \"Eggs\"],\n"
|
||||
+ "\"communicationPreferences\": {\"post\":true, \"email\":true}\n"
|
||||
+ "}";
|
||||
mvc.perform(post("/customers")
|
||||
.contentType(APPLICATION_JSON)
|
||||
.content(createCustomerRequestBody))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(redirectedUrlPattern("http://*/customers/1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonExistentCustomer_whenPatched_then404Returned() throws Exception {
|
||||
given(mockCustomerService.findCustomer("1")).willReturn(empty());
|
||||
|
||||
String patchInstructions = "[{\"op\":\"replace\",\"path\": \"/telephone\",\"value\":\"001-555-5678\"}]";
|
||||
mvc.perform(patch("/customers/1")
|
||||
.contentType(APPLICATION_JSON_PATCH_JSON)
|
||||
.content(patchInstructions))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingCustomer_whenPatched_thenReturnPatchedCustomer() throws Exception {
|
||||
Map<String, Boolean> communicationPreferences = new HashMap<>();
|
||||
communicationPreferences.put("post", true);
|
||||
communicationPreferences.put("email", true);
|
||||
Customer customer = new Customer("1", "001-555-1234", asList("Milk", "Eggs"), communicationPreferences);
|
||||
|
||||
given(mockCustomerService.findCustomer("1")).willReturn(of(customer));
|
||||
|
||||
String patchInstructions = "[{\"op\":\"replace\",\"path\": \"/telephone\",\"value\":\"001-555-5678\"}]";
|
||||
mvc.perform(patch("/customers/1")
|
||||
.contentType(APPLICATION_JSON_PATCH_JSON)
|
||||
.content(patchInstructions))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("1")))
|
||||
.andExpect(jsonPath("$.telephone", is("001-555-5678")))
|
||||
.andExpect(jsonPath("$.favorites", is(asList("Milk", "Eggs"))))
|
||||
.andExpect(jsonPath("$.communicationPreferences", is(communicationPreferences)));
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.web.controller.status;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.baeldung.config.MvcConfig;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = MvcConfig.class)
|
||||
@WebAppConfiguration
|
||||
@AutoConfigureWebClient
|
||||
public class ExampleControllerIntegrationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToController_thenReturnsStatusNotAcceptable() throws Exception {
|
||||
mockMvc.perform(get("/controller")).andExpect(status().isNotAcceptable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToException_thenReturnsStatusForbidden() throws Exception {
|
||||
mockMvc.perform(get("/exception")).andExpect(status().isForbidden());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user