Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
@@ -0,0 +1,61 @@
package com.baeldung.annotation.servletcomponentscan;
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.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
public class SpringBootWithServletComponentIntegrationTest {
@Autowired
private ServletContext servletContext;
@Test
public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() {
assertNotNull(servletContext);
assertNotNull(servletContext.getAttribute("servlet-context-attr"));
assertEquals("test", servletContext.getAttribute("servlet-context-attr"));
}
@Test
public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() {
assertNotNull(servletContext);
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNotNull(filterRegistration);
assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet"));
}
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenServletFilter_whenGetHello_thenRequestFiltered() {
ResponseEntity<String> responseEntity = this.restTemplate.getForEntity("/hello", String.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals("filtering hello", responseEntity.getBody());
}
@Test
public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() {
ResponseEntity<String> responseEntity = this.restTemplate.postForEntity("/echo", "echo", String.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals("filtering echo", responseEntity.getBody());
}
}
@@ -0,0 +1,49 @@
package com.baeldung.annotation.servletcomponentscan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
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.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
public class SpringBootWithoutServletComponentIntegrationTest {
@Autowired
private ServletContext servletContext;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenServletContext_whenAccessAttrs_thenNotFound() {
assertNull(servletContext.getAttribute("servlet-context-attr"));
}
@Test
public void givenServletFilter_whenGetHello_thenEndpointNotFound() {
ResponseEntity<String> responseEntity = this.restTemplate.getForEntity("/hello", String.class);
assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
}
@Test
public void givenServletContext_whenCheckFilterMappings_thenEmpty() {
assertNotNull(servletContext);
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNull(filterRegistration);
}
}
@@ -0,0 +1,70 @@
package com.baeldung.beanvalidation.application;
import com.baeldung.beanvalidation.application.controllers.UserController;
import com.baeldung.beanvalidation.application.repositories.UserRepository;
import java.nio.charset.Charset;
import static org.assertj.core.api.Assertions.assertThat;
import org.hamcrest.core.Is;
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.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {
@MockBean
private UserRepository userRepository;
@Autowired
UserController userController;
@Autowired
private MockMvc mockMvc;
@Test
public void whenUserControllerInjected_thenNotNull() throws Exception {
assertThat(userController).isNotNull();
}
@Test
public void whenGetRequestToUsers_thenCorrectResponse() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/users")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
@Test
public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception {
MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8"));
String user = "{\"name\": \"bob\", \"email\" : \"bob@domain.com\"}";
mockMvc.perform(MockMvcRequestBuilders.post("/users")
.content(user)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(textPlainUtf8));
}
@Test
public void whenPostRequestToUsersAndInValidUser_thenCorrectReponse() throws Exception {
String user = "{\"name\": \"\", \"email\" : \"bob@domain.com\"}";
mockMvc.perform(MockMvcRequestBuilders.post("/users")
.content(user)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory")))
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
}
@@ -0,0 +1,101 @@
package com.baeldung.displayallbeans;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.beans.BeansEndpoint.ContextBeans;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = { "management.port=0", "management.endpoints.web.exposure.include=*" })
public class DisplayBeanIntegrationTest {
@LocalServerPort
private int port;
@Value("${local.management.port}")
private int mgt;
@Autowired
private TestRestTemplate testRestTemplate;
@Autowired
private WebApplicationContext context;
private static final String ACTUATOR_PATH = "/actuator";
@Test
public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception {
ResponseEntity<String> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class);
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception {
ParameterizedTypeReference<Map<String, ContextBeans>> responseType = new ParameterizedTypeReference<Map<String, ContextBeans>>() {
};
RequestEntity<Void> requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans"))
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<Map<String, ContextBeans>> entity = this.testRestTemplate.exchange(requestEntity, responseType);
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception {
RequestEntity<Void> requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans"))
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<BeanActuatorResponse> entity = this.testRestTemplate.exchange(requestEntity, BeanActuatorResponse.class);
Collection<String> beanNamesList = entity.getBody()
.getBeans();
assertThat(beanNamesList).contains("fooController", "fooService");
}
@Test
public void givenWebApplicationContext_whenAccessGetBeanDefinitionNames_thenReturnsBeanNames() throws Exception {
String[] beanNames = context.getBeanDefinitionNames();
List<String> beanNamesList = Arrays.asList(beanNames);
assertThat(beanNamesList).contains("fooController", "fooService");
}
private static class BeanActuatorResponse {
private Map<String, Map<String, Map<String, Map<String, Object>>>> contexts;
public Collection<String> getBeans() {
return this.contexts.get("application")
.get("beans")
.keySet();
}
public Map<String, Map<String, Map<String, Map<String, Object>>>> getContexts() {
return contexts;
}
}
}
@@ -0,0 +1,47 @@
package com.baeldung.failureanalyzer;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.SpringApplication;
import com.baeldung.failureanalyzer.utils.ListAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class FailureAnalyzerAppIntegrationTest {
private static final String EXPECTED_ANALYSIS_DESCRIPTION_TITLE = "Description:";
private static final String EXPECTED_ANALYSIS_DESCRIPTION_CONTENT = "The bean myDAO could not be injected as com.baeldung.failureanalyzer.MyDAO because it is of type com.baeldung.failureanalyzer.MySecondDAO";
private static final String EXPECTED_ANALYSIS_ACTION_TITLE = "Action:";
private static final String EXPECTED_ANALYSIS_ACTION_CONTENT = "Consider creating a bean with name myDAO of type com.baeldung.failureanalyzer.MyDAO";
@BeforeEach
public void clearLogList() {
ListAppender.clearEventList();
}
@Test
public void givenBeanCreationErrorInContext_whenContextLoaded_thenFailureAnalyzerLogsReport() {
try {
SpringApplication.run(FailureAnalyzerApplication.class);
} catch (BeanCreationException e) {
Collection<String> allLoggedEntries = ListAppender.getEvents()
.stream()
.map(ILoggingEvent::getFormattedMessage)
.collect(Collectors.toList());
assertThat(allLoggedEntries).anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_DESCRIPTION_TITLE))
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_DESCRIPTION_CONTENT))
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_ACTION_TITLE))
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_ACTION_CONTENT));
return;
}
throw new IllegalStateException("Context load should be failing due to a BeanCreationException!");
}
}
@@ -0,0 +1,25 @@
package com.baeldung.failureanalyzer.utils;
import java.util.ArrayList;
import java.util.List;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
public class ListAppender extends AppenderBase<ILoggingEvent> {
static private List<ILoggingEvent> events = new ArrayList<>();
@Override
protected void append(ILoggingEvent eventObject) {
events.add(eventObject);
}
public static List<ILoggingEvent> getEvents() {
return events;
}
public static void clearEventList() {
events.clear();
}
}
@@ -0,0 +1,43 @@
package com.baeldung.git;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = CommitIdApplication.class)
@TestPropertySource(properties = { "spring.jmx.default-domain=test" })
public class CommitIdIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(CommitIdIntegrationTest.class);
@Value("${git.commit.message.short:UNKNOWN}")
private String commitMessage;
@Value("${git.branch:UNKNOWN}")
private String branch;
@Value("${git.commit.id:UNKNOWN}")
private String commitId;
@Test
public void whenInjecting_shouldDisplay() throws Exception {
LOG.info(commitId);
LOG.info(commitMessage);
LOG.info(branch);
assertThat(commitMessage).isNotEqualTo("UNKNOWN");
assertThat(branch).isNotEqualTo("UNKNOWN");
assertThat(commitId).isNotEqualTo("UNKNOWN");
}
}
@@ -0,0 +1,35 @@
package com.baeldung.intro;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class AppLiveTest {
@Autowired
private MockMvc mvc;
@Test
public void getIndex() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page")));
}
@Test
public void getLocal() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local")));
}
}
@@ -0,0 +1,109 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
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.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class)
@TestPropertySource(properties = {
"spring.jackson.date-format=yyyy-MM-dd HH:mm:ss"
})
public class ContactAppUnitTest {
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
TestRestTemplate restTemplate;
@LocalServerPort
int port;
String url;
@Before
public void before() {
url=String.format("http://localhost:%s", port);
}
@Test
public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenJsonFormatAnnotationAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/javaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test(expected = DateTimeParseException.class)
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenNotApplyFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}
@@ -0,0 +1,76 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
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.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class)
public class ContactAppWithObjectMapperCustomizerUnitTest {
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
TestRestTemplate restTemplate;
@LocalServerPort
int port;
String url;
@Before
public void before() {
url=String.format("http://localhost:%s", port);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
}
@@ -0,0 +1,170 @@
package com.baeldung.kong;
import com.baeldung.kong.domain.APIObject;
import com.baeldung.kong.domain.ConsumerObject;
import com.baeldung.kong.domain.KeyAuthObject;
import com.baeldung.kong.domain.PluginObject;
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.*;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URI;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
/**
* @author aiet
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class)
public class KongAdminAPILiveTest {
private String getStockPrice(String code) {
try {
return restTemplate.getForObject(new URI("http://localhost:8080/stock/" + code), String.class);
} catch (Exception ignored) {
}
return null;
}
@Before
public void init() {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() {
String response = getStockPrice("btc");
assertEquals("10000", response);
response = getStockPrice("eth");
assertEquals("N/A", response);
}
@Test
public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception {
restTemplate.delete("http://localhost:8001/apis/stock-api");
APIObject stockAPI = new APIObject("stock-api", "stock.api", "http://localhost:9090", "/");
HttpEntity<APIObject> apiEntity = new HttpEntity<>(stockAPI);
ResponseEntity<String> addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
assertEquals(HttpStatus.CREATED, addAPIResp.getStatusCode());
addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
assertEquals(HttpStatus.CONFLICT, addAPIResp.getStatusCode());
String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class);
assertTrue(apiListResp.contains("stock-api"));
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "stock.api");
RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc"));
ResponseEntity<String> stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals("10000", stockPriceResp.getBody());
}
@Test
public void givenKongAdminAPI_whenAddAPIConsumer_thenAdded() {
restTemplate.delete("http://localhost:8001/consumers/eugenp");
ConsumerObject consumer = new ConsumerObject("eugenp");
HttpEntity<ConsumerObject> addConsumerEntity = new HttpEntity<>(consumer);
ResponseEntity<String> addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers/", addConsumerEntity, String.class);
assertEquals(HttpStatus.CREATED, addConsumerResp.getStatusCode());
addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers", addConsumerEntity, String.class);
assertEquals(HttpStatus.CONFLICT, addConsumerResp.getStatusCode());
String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class);
assertTrue(consumerListResp.contains("eugenp"));
}
@Test
public void givenAPI_whenEnableAuth_thenAnonymousDenied() throws Exception {
String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class);
if (!apiListResp.contains("stock-api")) {
givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong();
}
PluginObject authPlugin = new PluginObject("key-auth");
ResponseEntity<String> enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class);
assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode());
String pluginsResp = restTemplate.getForObject("http://localhost:8001/apis/stock-api/plugins", String.class);
assertTrue(pluginsResp.contains("key-auth"));
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "stock.api");
RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc"));
ResponseEntity<String> stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals(HttpStatus.UNAUTHORIZED, stockPriceResp.getStatusCode());
}
@Test
public void givenAPIAuthEnabled_whenAddKey_thenAccessAllowed() throws Exception {
String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class);
if (!apiListResp.contains("stock-api")) {
givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong();
}
String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class);
if (!consumerListResp.contains("eugenp")) {
givenKongAdminAPI_whenAddAPIConsumer_thenAdded();
}
PluginObject authPlugin = new PluginObject("key-auth");
ResponseEntity<String> enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class);
assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode());
final String consumerKey = "eugenp.pass";
KeyAuthObject keyAuth = new KeyAuthObject(consumerKey);
ResponseEntity<String> keyAuthResp = restTemplate.postForEntity("http://localhost:8001/consumers/eugenp/key-auth", new HttpEntity<>(keyAuth), String.class);
assertTrue(HttpStatus.CREATED == keyAuthResp.getStatusCode() || HttpStatus.CONFLICT == keyAuthResp.getStatusCode());
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "stock.api");
headers.set("apikey", consumerKey);
RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc"));
ResponseEntity<String> stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals("10000", stockPriceResp.getBody());
headers.set("apikey", "wrongpass");
requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc"));
stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals(HttpStatus.FORBIDDEN, stockPriceResp.getStatusCode());
}
@Test
public void givenAdminAPIProxy_whenAddAPIViaProxy_thenAPIAdded() throws Exception {
APIObject adminAPI = new APIObject("admin-api", "admin.api", "http://localhost:8001", "/admin-api");
HttpEntity<APIObject> apiEntity = new HttpEntity<>(adminAPI);
ResponseEntity<String> addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode());
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "admin.api");
APIObject baeldungAPI = new APIObject("baeldung-api", "baeldung.com", "http://ww.baeldung.com", "/");
RequestEntity<APIObject> requestEntity = new RequestEntity<>(baeldungAPI, headers, HttpMethod.POST, new URI("http://localhost:8000/admin-api/apis"));
addAPIResp = restTemplate.exchange(requestEntity, String.class);
assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode());
}
}
@@ -0,0 +1,75 @@
package com.baeldung.kong;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
import java.net.URI;
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.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.kong.domain.APIObject;
import com.baeldung.kong.domain.TargetObject;
import com.baeldung.kong.domain.UpstreamObject;
/**
* @author aiet
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class, properties = "server.servlet.contextPath=/springbootapp")
public class KongLoadBalanceLiveTest {
@Before
public void init() {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception {
UpstreamObject upstream = new UpstreamObject("stock.api.service");
ResponseEntity<String> addUpstreamResp = restTemplate.postForEntity("http://localhost:8001/upstreams", new HttpEntity<>(upstream), String.class);
assertTrue(HttpStatus.CREATED == addUpstreamResp.getStatusCode() || HttpStatus.CONFLICT == addUpstreamResp.getStatusCode());
TargetObject testTarget = new TargetObject("localhost:8080", 10);
ResponseEntity<String> addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(testTarget), String.class);
assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode());
TargetObject releaseTarget = new TargetObject("localhost:9090", 40);
addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(releaseTarget), String.class);
assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode());
APIObject stockAPI = new APIObject("balanced-stock-api", "balanced.stock.api", "http://stock.api.service", "/");
HttpEntity<APIObject> apiEntity = new HttpEntity<>(stockAPI);
ResponseEntity<String> addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode());
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "balanced.stock.api");
for (int i = 0; i < 1000; i++) {
RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc"));
ResponseEntity<String> stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals("10000", stockPriceResp.getBody());
}
int releaseCount = restTemplate.getForObject("http://localhost:9090/springbootapp/stock/reqcount", Integer.class);
int testCount = restTemplate.getForObject("http://localhost:8080/springbootapp/stock/reqcount", Integer.class);
assertTrue(Math.round(releaseCount * 1.0 / testCount) == 4);
}
}
@@ -0,0 +1,54 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class APIObject {
public APIObject() {
}
public APIObject(String name, String hosts, String upstream_url, String uris) {
this.name = name;
this.hosts = hosts;
this.upstream_url = upstream_url;
this.uris = uris;
}
private String name;
private String hosts;
private String upstream_url;
private String uris;
public String getUris() {
return uris;
}
public void setUris(String uris) {
this.uris = uris;
}
public String getUpstream_url() {
return upstream_url;
}
public void setUpstream_url(String upstream_url) {
this.upstream_url = upstream_url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHosts() {
return hosts;
}
public void setHosts(String hosts) {
this.hosts = hosts;
}
}
@@ -0,0 +1,35 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class ConsumerObject {
private String username;
private String custom_id;
public ConsumerObject(String username) {
this.username = username;
}
public ConsumerObject(String username, String custom_id) {
this.username = username;
this.custom_id = custom_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCustom_id() {
return custom_id;
}
public void setCustom_id(String custom_id) {
this.custom_id = custom_id;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class KeyAuthObject {
public KeyAuthObject(String key) {
this.key = key;
}
private String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class PluginObject {
private String name;
private String consumer_id;
public PluginObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getConsumer_id() {
return consumer_id;
}
public void setConsumer_id(String consumer_id) {
this.consumer_id = consumer_id;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class TargetObject {
public TargetObject(String target, int weight) {
this.target = target;
this.weight = weight;
}
private String target;
private int weight;
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class UpstreamObject {
public UpstreamObject(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.servletinitializer;
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
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.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.baeldung.servletinitializer.WarInitializerApplication.WarInitializerController;
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = WarInitializerController.class)
public class WarInitializerApplicationIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void whenContextRootUrlIsAccessed_thenStatusIsOk() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().is(200));
}
@Test
public void whenContextRootUrlIsAccesed_thenCorrectStringIsReturned() throws Exception {
mockMvc.perform(get("/"))
.andExpect(content().string(containsString("WarInitializerApplication is up and running!")));
}
}
@@ -0,0 +1,62 @@
package com.baeldung.toggle;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
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.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = ToggleApplication.class)
@AutoConfigureMockMvc
public class ToggleIntegrationTest {
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenFeaturePropertyFalse_whenIncreaseSalary_thenNoIncrease() throws Exception {
Employee emp = new Employee(1, 2000);
employeeRepository.save(emp);
System.setProperty("employee.feature", "false");
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
emp = employeeRepository.findById(1L).orElse(null);
assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5);
}
@Test
public void givenFeaturePropertyTrue_whenIncreaseSalary_thenIncrease() throws Exception {
Employee emp = new Employee(1, 2000);
employeeRepository.save(emp);
System.setProperty("employee.feature", "true");
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
emp = employeeRepository.findById(1L).orElse(null);
assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.utils;
import com.baeldung.utils.controller.UtilsController;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class UtilsControllerIntegrationTest {
@InjectMocks
private UtilsController utilsController;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build();
}
@Test
public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception {
String param = "testparam";
this.mockMvc.perform(post("/setParam").param("param", param).sessionAttr("parameter", param)).andExpect(status().isOk());
}
}
@@ -0,0 +1,17 @@
package org.baeldung.boot;
import org.baeldung.session.exception.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@TestPropertySource("classpath:exception.properties")
public class ApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,17 @@
package org.baeldung.boot;
import org.baeldung.demo.DemoApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class DemoApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,29 @@
package org.baeldung.boot.jsoncomponent;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.scene.paint.Color;
import org.baeldung.boot.jsoncomponent.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
@JsonTest
@RunWith(SpringRunner.class)
public class UserJsonDeserializerIntegrationTest {
@Autowired
private ObjectMapper objectMapper;
@Test
public void testDeserialize() throws IOException {
User user = objectMapper.readValue("{\"favoriteColor\":\"#f0f8ff\"}", User.class);
assertEquals(Color.ALICEBLUE, user.getFavoriteColor());
}
}
@@ -0,0 +1,28 @@
package org.baeldung.boot.jsoncomponent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.scene.paint.Color;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import org.baeldung.boot.jsoncomponent.User;
@JsonTest
@RunWith(SpringRunner.class)
public class UserJsonSerializerIntegrationTest {
@Autowired
private ObjectMapper objectMapper;
@Test
public void testSerialization() throws JsonProcessingException {
String json = objectMapper.writeValueAsString(new User(Color.ALICEBLUE));
assertEquals("{\"favoriteColor\":\"#f0f8ff\"}", json);
}
}
@@ -0,0 +1,35 @@
package org.baeldung.boot.repository;
import static org.junit.Assert.assertThat;
import org.baeldung.boot.DemoApplicationIntegrationTest;
import org.baeldung.demo.model.Foo;
import org.baeldung.demo.repository.FooRepository;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.is;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class FooRepositoryIntegrationTest extends DemoApplicationIntegrationTest {
@Autowired
private FooRepository fooRepository;
@Before
public void setUp() {
fooRepository.save(new Foo("Foo"));
fooRepository.save(new Foo("Bar"));
}
@Test
public void testFindByName() {
Foo foo = fooRepository.findByName("Bar");
assertThat(foo, notNullValue());
assertThat(foo.getId(), is(2));
}
}
@@ -0,0 +1,30 @@
package org.baeldung.boot.repository;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.baeldung.boot.DemoApplicationIntegrationTest;
import org.baeldung.demo.model.Foo;
import org.baeldung.demo.repository.FooRepository;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class HibernateSessionIntegrationTest extends DemoApplicationIntegrationTest {
@Autowired
private FooRepository fooRepository;
@Test
public void whenSavingWithCurrentSession_thenThrowNoException() {
Foo foo = new Foo("Exception Solved");
fooRepository.save(foo);
foo = null;
foo = fooRepository.findByName("Exception Solved");
assertThat(foo, notNullValue());
assertThat(foo.getId(), is(1));
assertThat(foo.getName(), is("Exception Solved"));
}
}
@@ -0,0 +1,23 @@
package org.baeldung.boot.repository;
import org.baeldung.boot.ApplicationIntegrationTest;
import org.baeldung.demo.model.Foo;
import org.baeldung.session.exception.repository.FooRepository;
import org.hibernate.HibernateException;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.TestPropertySource;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@TestPropertySource("classpath:exception-hibernate.properties")
public class NoHibernateSessionIntegrationTest extends ApplicationIntegrationTest {
@Autowired
private FooRepository fooRepository;
@Test(expected = HibernateException.class)
public void whenSavingWithoutCurrentSession_thenThrowException() {
Foo foo = new Foo("Exception Thrown");
fooRepository.save(foo);
}
}
@@ -0,0 +1,50 @@
package org.baeldung.converter;
import com.baeldung.toggle.Employee;
import org.baeldung.boot.Application;
import org.baeldung.boot.domain.Modes;
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.core.convert.ConversionService;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.math.BigDecimal;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class CustomConverterIntegrationTest {
@Autowired
ConversionService conversionService;
@Test
public void whenConvertStringToIntegerUsingDefaultConverter_thenSuccess() {
assertThat(conversionService.convert("25", Integer.class)).isEqualTo(25);
}
@Test
public void whenConvertStringToEmployee_thenSuccess() {
Employee employee = conversionService.convert("1,50000.00", Employee.class);
Employee actualEmployee = new Employee(1, 50000.00);
assertThat(conversionService.convert("1,50000.00", Employee.class)).isEqualToComparingFieldByField(actualEmployee);
}
@Test
public void whenConvertStringToEnum_thenSuccess() {
assertThat(conversionService.convert("ALPHA", Modes.class)).isEqualTo(Modes.ALPHA);
}
@Test
public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() {
assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)).isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN));
assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)).isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23)));
assertThat(conversionService.convert("2.32", BigDecimal.class)).isEqualTo(BigDecimal.valueOf(2.32));
}
}
@@ -0,0 +1,31 @@
package org.baeldung.converter.controller;
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.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.baeldung.boot.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class)
@AutoConfigureMockMvc
public class StringToEmployeeConverterControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void getStringToEmployeeTest() throws Exception {
mockMvc.perform(get("/string-to-employee?employee=1,2000")).andDo(print()).andExpect(jsonPath("$.id", is(1))).andExpect(jsonPath("$.salary", is(2000.0))).andExpect(status().isOk());
}
}
@@ -0,0 +1,71 @@
package org.baeldung.demo.boottest;
import org.baeldung.demo.boottest.Employee;
import org.baeldung.demo.boottest.EmployeeRestController;
import org.baeldung.demo.boottest.EmployeeService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.internal.verification.VerificationModeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
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.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(EmployeeRestController.class)
public class EmployeeControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@MockBean
private EmployeeService service;
@Before
public void setUp() throws Exception {
}
@Test
public void whenPostEmployee_thenCreateEmployee() throws Exception {
Employee alex = new Employee("alex");
given(service.save(Mockito.any())).willReturn(alex);
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(alex))).andExpect(status().isCreated()).andExpect(jsonPath("$.name", is("alex")));
verify(service, VerificationModeFactory.times(1)).save(Mockito.any());
reset(service);
}
@Test
public void givenEmployees_whenGetEmployees_thenReturnJsonArray() throws Exception {
Employee alex = new Employee("alex");
Employee john = new Employee("john");
Employee bob = new Employee("bob");
List<Employee> allEmployees = Arrays.asList(alex, john, bob);
given(service.getAllEmployees()).willReturn(allEmployees);
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(3))).andExpect(jsonPath("$[0].name", is(alex.getName()))).andExpect(jsonPath("$[1].name", is(john.getName())))
.andExpect(jsonPath("$[2].name", is(bob.getName())));
verify(service, VerificationModeFactory.times(1)).getAllEmployees();
reset(service);
}
}
@@ -0,0 +1,71 @@
package org.baeldung.demo.boottest;
import org.baeldung.demo.boottest.Employee;
import org.baeldung.demo.boottest.EmployeeRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@DataJpaTest
public class EmployeeRepositoryIntegrationTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private EmployeeRepository employeeRepository;
@Test
public void whenFindByName_thenReturnEmployee() {
Employee alex = new Employee("alex");
entityManager.persistAndFlush(alex);
Employee found = employeeRepository.findByName(alex.getName());
assertThat(found.getName()).isEqualTo(alex.getName());
}
@Test
public void whenInvalidName_thenReturnNull() {
Employee fromDb = employeeRepository.findByName("doesNotExist");
assertThat(fromDb).isNull();
}
@Test
public void whenFindById_thenReturnEmployee() {
Employee emp = new Employee("test");
entityManager.persistAndFlush(emp);
Employee fromDb = employeeRepository.findById(emp.getId()).orElse(null);
assertThat(fromDb.getName()).isEqualTo(emp.getName());
}
@Test
public void whenInvalidId_thenReturnNull() {
Employee fromDb = employeeRepository.findById(-11l).orElse(null);
assertThat(fromDb).isNull();
}
@Test
public void givenSetOfEmployees_whenFindAll_thenReturnAllEmployees() {
Employee alex = new Employee("alex");
Employee ron = new Employee("ron");
Employee bob = new Employee("bob");
entityManager.persist(alex);
entityManager.persist(bob);
entityManager.persist(ron);
entityManager.flush();
List<Employee> allEmployees = employeeRepository.findAll();
assertThat(allEmployees).hasSize(3).extracting(Employee::getName).containsOnly(alex.getName(), ron.getName(), bob.getName());
}
}
@@ -0,0 +1,80 @@
package org.baeldung.demo.boottest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
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.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.IOException;
import java.util.List;
import org.baeldung.demo.DemoApplication;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class)
@AutoConfigureMockMvc
// @TestPropertySource(locations = "classpath:application-integrationtest.properties")
@AutoConfigureTestDatabase
public class EmployeeRestControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@Autowired
private EmployeeRepository repository;
@After
public void resetDb() {
repository.deleteAll();
}
@Test
public void whenValidInput_thenCreateEmployee() throws IOException, Exception {
Employee bob = new Employee("bob");
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(bob)));
List<Employee> found = repository.findAll();
assertThat(found).extracting(Employee::getName).containsOnly("bob");
}
@Test
public void givenEmployees_whenGetEmployees_thenStatus200() throws Exception {
createTestEmployee("bob");
createTestEmployee("alex");
// @formatter:off
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
.andExpect(jsonPath("$[0].name", is("bob")))
.andExpect(jsonPath("$[1].name", is("alex")));
// @formatter:on
}
//
private void createTestEmployee(String name) {
Employee emp = new Employee(name);
repository.saveAndFlush(emp);
}
}
@@ -0,0 +1,127 @@
package org.baeldung.demo.boottest;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.internal.verification.VerificationModeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class EmployeeServiceImplIntegrationTest {
@TestConfiguration
static class EmployeeServiceImplTestContextConfiguration {
@Bean
public EmployeeService employeeService() {
return new EmployeeServiceImpl();
}
}
@Autowired
private EmployeeService employeeService;
@MockBean
private EmployeeRepository employeeRepository;
@Before
public void setUp() {
Employee john = new Employee("john");
john.setId(11L);
Employee bob = new Employee("bob");
Employee alex = new Employee("alex");
List<Employee> allEmployees = Arrays.asList(john, bob, alex);
Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john);
Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex);
Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null);
Mockito.when(employeeRepository.findById(john.getId())).thenReturn(Optional.of(john));
Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees);
Mockito.when(employeeRepository.findById(-99L)).thenReturn(Optional.empty());
}
@Test
public void whenValidName_thenEmployeeShouldBeFound() {
String name = "alex";
Employee found = employeeService.getEmployeeByName(name);
assertThat(found.getName()).isEqualTo(name);
}
@Test
public void whenInValidName_thenEmployeeShouldNotBeFound() {
Employee fromDb = employeeService.getEmployeeByName("wrong_name");
assertThat(fromDb).isNull();
verifyFindByNameIsCalledOnce("wrong_name");
}
@Test
public void whenValidName_thenEmployeeShouldExist() {
boolean doesEmployeeExist = employeeService.exists("john");
assertThat(doesEmployeeExist).isEqualTo(true);
verifyFindByNameIsCalledOnce("john");
}
@Test
public void whenNonExistingName_thenEmployeeShouldNotExist() {
boolean doesEmployeeExist = employeeService.exists("some_name");
assertThat(doesEmployeeExist).isEqualTo(false);
verifyFindByNameIsCalledOnce("some_name");
}
@Test
public void whenValidId_thenEmployeeShouldBeFound() {
Employee fromDb = employeeService.getEmployeeById(11L);
assertThat(fromDb.getName()).isEqualTo("john");
verifyFindByIdIsCalledOnce();
}
@Test
public void whenInValidId_thenEmployeeShouldNotBeFound() {
Employee fromDb = employeeService.getEmployeeById(-99L);
verifyFindByIdIsCalledOnce();
assertThat(fromDb).isNull();
}
@Test
public void given3Employees_whengetAll_thenReturn3Records() {
Employee alex = new Employee("alex");
Employee john = new Employee("john");
Employee bob = new Employee("bob");
List<Employee> allEmployees = employeeService.getAllEmployees();
verifyFindAllEmployeesIsCalledOnce();
assertThat(allEmployees).hasSize(3).extracting(Employee::getName).contains(alex.getName(), john.getName(), bob.getName());
}
private void verifyFindByNameIsCalledOnce(String name) {
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findByName(name);
Mockito.reset(employeeRepository);
}
private void verifyFindByIdIsCalledOnce() {
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findById(Mockito.anyLong());
Mockito.reset(employeeRepository);
}
private void verifyFindAllEmployeesIsCalledOnce() {
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findAll();
Mockito.reset(employeeRepository);
}
}
@@ -0,0 +1,14 @@
package org.baeldung.demo.boottest;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
class JsonUtil {
static byte[] toJson(Object object) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsBytes(object);
}
}
@@ -0,0 +1,72 @@
package org.baeldung.repository;
import org.baeldung.boot.config.H2JpaConfig;
import org.baeldung.model.User;
import org.junit.After;
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.test.context.junit4.SpringRunner;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by adam.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = H2JpaConfig.class)
public class UserRepositoryIntegrationTest {
private final String USER_NAME_ADAM = "Adam";
private final Integer ACTIVE_STATUS = 1;
@Autowired
private UserRepository userRepository;
@Test
public void givenEmptyDBWhenFindOneByNameThenReturnEmptyOptional() {
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
assertThat(foundUser.isPresent()).isEqualTo(false);
}
@Test
public void givenUserInDBWhenFindOneByNameThenReturnOptionalWithUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
userRepository.save(user);
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
assertThat(foundUser.isPresent()).isEqualTo(true);
assertThat(foundUser
.get()
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
CompletableFuture<User> userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS);
assertThat(userByStatus
.get()
.getName()).isEqualTo(USER_NAME_ADAM);
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
}