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,29 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Example1IntegrationTest {
@Test
public void test1a() {
block(3000);
}
@Test
public void test1b() {
block(3000);
}
public static void block(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}
@@ -0,0 +1,29 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Example2IntegrationTest {
@Test
public void test1a() {
block(3000);
}
@Test
public void test1b() {
block(3000);
}
public static void block(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
System.out.println("Thread Interrupted");
}
}
}
@@ -0,0 +1,24 @@
package com.baeldung;
import org.junit.Test;
import org.junit.experimental.ParallelComputer;
import org.junit.runner.Computer;
import org.junit.runner.JUnitCore;
public class ParallelIntegrationTest {
@Test
public void runTests() {
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new Computer(), classes);
}
@Test
public void runTestsInParallel() {
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
}
}
@@ -0,0 +1,18 @@
package com.baeldung;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@Ignore
public class Spring5ApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,52 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = Spring5JUnit4ConcurrentIntegrationTest.SimpleConfiguration.class)
public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContextAware, InitializingBean {
@Configuration
public static class SimpleConfiguration {
}
private ApplicationContext applicationContext;
private boolean beanInitialized = false;
@Override
public final void afterPropertiesSet() throws Exception {
this.beanInitialized = true;
}
@Override
public final void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Test
public final void verifyApplicationContextSet() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
assertNotNull("The application context should have been set due to ApplicationContextAware semantics.", this.applicationContext);
}
@Test
public final void verifyBeanInitialized() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
assertTrue("This test bean should have been initialized due to InitializingBean semantics.", this.beanInitialized);
}
}
@@ -0,0 +1,23 @@
package com.baeldung;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.annotationconfigvscomponentscan.components.AccountService;
import com.baeldung.annotationconfigvscomponentscan.components.UserService;
public class SpringXMLConfigurationIntegrationTest {
@Test
public void givenContextAnnotationConfigOrContextComponentScan_whenDependenciesAndBeansAnnotated_thenNoXMLNeeded() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:annotationconfigvscomponentscan-beans.xml");
UserService userService = context.getBean(UserService.class);
AccountService accountService = context.getBean(AccountService.class);
Assert.assertNotNull(userService);
Assert.assertNotNull(accountService);
Assert.assertNotNull(userService.getAccountService());
}
}
@@ -0,0 +1,42 @@
package com.baeldung.functional;
import static org.junit.Assert.assertTrue;
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 org.springframework.web.context.support.GenericWebApplicationContext;
import com.baeldung.Spring5Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class)
public class BeanRegistrationIntegrationTest {
@Autowired
private GenericWebApplicationContext context;
@Test
public void whenRegisterBean_thenOk() {
context.registerBean(MyService.class, () -> new MyService());
MyService myService = (MyService) context.getBean("com.baeldung.functional.MyService");
assertTrue(myService.getRandomNumber() < 10);
}
@Test
public void whenRegisterBeanWithName_thenOk() {
context.registerBean("mySecondService", MyService.class, () -> new MyService());
MyService mySecondService = (MyService) context.getBean("mySecondService");
assertTrue(mySecondService.getRandomNumber() < 10);
}
@Test
public void whenRegisterBeanWithCallback_thenOk() {
context.registerBean("myCallbackService", MyService.class, () -> new MyService(), bd -> bd.setAutowireCandidate(false));
MyService myCallbackService = (MyService) context.getBean("myCallbackService");
assertTrue(myCallbackService.getRandomNumber() < 10);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.hikari;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApplicationWithHikariConnectionPool {
public static void main(String[] args) {
SpringApplication.run(ApplicationWithHikariConnectionPool.class, args);
}
}
@@ -0,0 +1,26 @@
package com.baeldung.hikari;
import static org.junit.Assert.*;
import javax.sql.DataSource;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HikariIntegrationTest {
@Autowired
private DataSource dataSource;
@Test
public void hikariConnectionPoolIsConfigured() {
assertEquals("com.zaxxer.hikari.HikariDataSource", dataSource.getClass()
.getName());
}
}
@@ -0,0 +1,55 @@
package com.baeldung.jdbc.autogenkey;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert;
@RunWith(SpringRunner.class)
@Ignore
public class GetAutoGenKeyByJDBCIntTest {
@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:autogenkey-db.properties")
@ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey.repository" })
public static class SpringConfig {
}
@Autowired
MessageRepositorySimpleJDBCInsert messageRepositorySimpleJDBCInsert;
@Autowired
MessageRepositoryJDBCTemplate messageRepositoryJDBCTemplate;
final String MESSAGE_CONTENT = "Test";
@Test
public void insertJDBC_whenLoadMessageByKey_thenGetTheSameMessage() {
long key = messageRepositoryJDBCTemplate.insert(MESSAGE_CONTENT);
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
assertEquals(MESSAGE_CONTENT, loadedMessage);
}
@Test
public void insertSimpleInsert_whenLoadMessageKey_thenGetTheSameMessage() {
long key = messageRepositorySimpleJDBCInsert.insert(MESSAGE_CONTENT);
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
assertEquals(MESSAGE_CONTENT, loadedMessage);
}
}
@@ -0,0 +1,41 @@
package com.baeldung.jsonb;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.time.LocalDate;
import org.junit.Ignore;
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.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Ignore
public class JsonbIntegrationTest {
@Autowired
private TestRestTemplate template;
@Test
public void givenId_whenUriIsPerson_thenGetPerson() {
ResponseEntity<Person> response = template
.getForEntity("/person/1", Person.class);
Person person = response.getBody();
assertTrue(person.equals(new Person(2, "Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0))));
}
@Test
public void whenSendPostAPerson_thenGetOkStatus() {
ResponseEntity<Boolean> response = template.withBasicAuth("user","password").
postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class);
assertTrue(response.getBody());
}
}
@@ -0,0 +1,18 @@
package com.baeldung.jupiter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.test.context.junit.jupiter.EnabledIf;
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@EnabledIf(
expression = "#{systemProperties['java.version'].startsWith('1.8')}",
reason = "Enabled on Java 8"
)
public @interface EnabledOnJava8 {
}
@@ -0,0 +1,50 @@
package com.baeldung.jupiter;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.DisabledIf;
import org.springframework.test.context.junit.jupiter.EnabledIf;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(Spring5EnabledAnnotationIntegrationTest.Config.class)
@TestPropertySource(properties = { "tests.enabled=true" })
public class Spring5EnabledAnnotationIntegrationTest {
@Configuration
static class Config {
}
@EnabledIf("true")
@Test
void givenEnabledIfLiteral_WhenTrue_ThenTestExecuted() {
assertTrue(true);
}
@EnabledIf(expression = "${tests.enabled}", loadContext = true)
@Test
void givenEnabledIfExpression_WhenTrue_ThenTestExecuted() {
assertTrue(true);
}
@EnabledIf("#{systemProperties['java.version'].startsWith('1.8')}")
@Test
void givenEnabledIfSpel_WhenTrue_ThenTestExecuted() {
assertTrue(true);
}
@EnabledOnJava8
@Test
void givenEnabledOnJava8_WhenTrue_ThenTestExecuted() {
assertTrue(true);
}
@DisabledIf("#{systemProperties['java.version'].startsWith('1.7')}")
@Test
void givenDisabledIf_WhenTrue_ThenTestNotExecuted() {
assertTrue(true);
}
}
@@ -0,0 +1,37 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringJUnit5Config(TestConfig.class)
@DisplayName("@SpringJUnit5Config Tests")
class Spring5JUnit5ComposedAnnotationIntegrationTest {
@Autowired
private Task task;
@Autowired
private List<Task> tasks;
@Test
@DisplayName("ApplicationContext injected into method")
void givenAMethodName_whenInjecting_thenApplicationContextInjectedIntoMethod(ApplicationContext applicationContext) {
assertNotNull(applicationContext, "ApplicationContext should have been injected into method by Spring");
assertEquals(this.task, applicationContext.getBean("taskName", Task.class));
}
@Test
@DisplayName("Spring @Beans injected into fields")
void givenAnObject_whenInjecting_thenSpringBeansInjected() {
assertNotNull(task, "Task should have been @Autowired by Spring");
assertEquals("taskName", task.getName(), "Task's name");
assertEquals(1, tasks.size(), "Number of Tasks in context");
}
}
@@ -0,0 +1,24 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestConfig.class)
class Spring5JUnit5IntegrationTest {
@Autowired
private Task task;
@Test
void givenAMethodName_whenInjecting_thenApplicationContextInjectedIntoMetho(ApplicationContext applicationContext) {
assertNotNull(applicationContext, "ApplicationContext should have been injected by Spring");
assertEquals(this.task, applicationContext.getBean("taskName", Task.class));
}
}
@@ -0,0 +1,25 @@
package com.baeldung.jupiter;
import com.baeldung.Example1IntegrationTest;
import com.baeldung.Example2IntegrationTest;
import org.junit.experimental.ParallelComputer;
import org.junit.jupiter.api.Test;
import org.junit.runner.Computer;
import org.junit.runner.JUnitCore;
class Spring5JUnit5ParallelIntegrationTest {
@Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() {
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
}
@Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() {
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new Computer(), classes);
}
}
@@ -0,0 +1,31 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.Test;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
class Spring5Java8NewFeaturesIntegrationTest {
@FunctionalInterface
public interface FunctionalInterfaceExample<Input, Result> {
Result reverseString(Input input);
}
public class StringUtils {
FunctionalInterfaceExample<String, String> functionLambdaString = s -> Pattern.compile(" +")
.splitAsStream(s)
.map(word -> new StringBuilder(word).reverse())
.collect(Collectors.joining(" "));
}
@Test
void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() throws Exception {
Supplier<StringUtils> stringUtilsSupplier = StringUtils::new;
assertEquals(stringUtilsSupplier.get().functionLambdaString.reverseString("hello"), "olleh");
}
}
@@ -0,0 +1,33 @@
package com.baeldung.jupiter;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @SpringJUnitConfig(SpringJUnitConfigTest.Config.class) is equivalent to:
*
* @ExtendWith(SpringExtension.class)
* @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class )
*
*/
@SpringJUnitConfig(SpringJUnitConfigIntegrationTest.Config.class)
public class SpringJUnitConfigIntegrationTest {
@Configuration
static class Config {
}
@Autowired
private ApplicationContext applicationContext;
@Test
void givenAppContext_WhenInjected_ThenItShouldNotBeNull() {
assertNotNull(applicationContext);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.jupiter;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.web.context.WebApplicationContext;
/**
* @SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) is equivalent to:
*
* @ExtendWith(SpringExtension.class)
* @WebAppConfiguration
* @ContextConfiguration(classes = SpringJUnitWebConfigTest.Config.class )
*
*/
@SpringJUnitWebConfig(SpringJUnitWebConfigIntegrationTest.Config.class)
public class SpringJUnitWebConfigIntegrationTest {
@Configuration
static class Config {
}
@Autowired
private WebApplicationContext webAppContext;
@Test
void givenWebAppContext_WhenInjected_ThenItShouldNotBeNull() {
assertNotNull(webAppContext);
}
}
@@ -0,0 +1,180 @@
package com.baeldung.restdocs;
import com.baeldung.restdocs.CrudInput;
import com.baeldung.restdocs.SpringRestDocsApplication;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Rule;
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.hateoas.MediaTypes;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.restdocs.constraints.ConstraintDescriptions;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.singletonList;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.collectionToDelimitedString;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringRestDocsApplication.class)
public class ApiDocumentationJUnit4IntegrationTest {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");
@Autowired
private WebApplicationContext context;
@Autowired
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.build();
}
@Test
public void indexExample() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andDo(document("index-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(linkWithRel("crud").description("The CRUD resource")), responseFields(subsectionWithPath("_links").description("Links to other resources")),
responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`"))));
}
@Test
public void crudGetExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 1L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class);
this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudCreateExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 2L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andDo(document("crud-create-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input"), fieldWithPath("title").description("The title of the input"),
fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudDeleteExample() throws Exception {
this.mockMvc.perform(delete("/crud/{id}", 10))
.andExpect(status().isOk())
.andDo(document("crud-delete-example", pathParameters(parameterWithName("id").description("The id of the input to delete"))));
}
@Test
public void crudPatchExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PATCH");
String tagLocation = this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model Patch");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk());
}
@Test
public void crudPutExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PUT");
String tagLocation = this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isAccepted())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isAccepted());
}
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,173 @@
package com.baeldung.restdocs;
import static java.util.Collections.singletonList;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.collectionToDelimitedString;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.hateoas.MediaTypes;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.restdocs.constraints.ConstraintDescriptions;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.restdocs.CrudInput;
import com.baeldung.restdocs.SpringRestDocsApplication;
import com.fasterxml.jackson.databind.ObjectMapper;
@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
@SpringBootTest(classes = SpringRestDocsApplication.class)
public class ApiDocumentationJUnit5IntegrationTest {
@Autowired
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@BeforeEach
public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentation))
.alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.build();
}
@Test
public void indexExample() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andDo(document("index-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(linkWithRel("crud").description("The CRUD resource")), responseFields(subsectionWithPath("_links").description("Links to other resources")),
responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`"))));
}
@Test
public void crudGetExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 1L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class);
this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudCreateExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 2L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andDo(document("crud-create-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input"), fieldWithPath("title").description("The title of the input"),
fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudDeleteExample() throws Exception {
this.mockMvc.perform(delete("/crud/{id}", 10))
.andExpect(status().isOk())
.andDo(document("crud-delete-example", pathParameters(parameterWithName("id").description("The id of the input to delete"))));
}
@Test
public void crudPatchExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PATCH");
String tagLocation = this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model Patch");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk());
}
@Test
public void crudPutExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PUT");
String tagLocation = this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isAccepted())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isAccepted());
}
@Test
public void contextLoads() {
}
}