BAEL-6131: Moving REST Docs to a separate package (#16273)

* BAEL-6131:  Moving REST Docs to a separate package

* BAEL-6131:  Removed askii-doctor configurations
This commit is contained in:
Eugene Kovko
2024-04-08 18:17:38 +02:00
committed by GitHub
parent 4b5e5192d9
commit 930f1ce0a5
19 changed files with 138 additions and 27 deletions
+12
View File
@@ -0,0 +1,12 @@
#folders#
.idea
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
+8
View File
@@ -0,0 +1,8 @@
## Spring 5 REST Docs
This module contains articles about Spring 5
### Relevant Articles
- [Introduction to Spring REST Docs](https://www.baeldung.com/spring-rest-docs)
- [Document Query Parameters with Spring REST Docs](https://www.baeldung.com/spring-rest-document-query-parameters)
+118
View File
@@ -0,0 +1,118 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-5</name>
<packaging>jar</packaging>
<description>spring 5 sample project about new features</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-3</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<!-- restdocs -->
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-restassured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-webtestclient</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.Spring5Application</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>${asciidoctor-plugin.version}</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>book</doctype>
<attributes>
<snippets>${snippetsDirectory}</snippets>
</attributes>
<sourceDirectory>src/docs/asciidocs</sourceDirectory>
<outputDirectory>target/generated-docs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<asciidoctor-plugin.version>2.2.6</asciidoctor-plugin.version>
<snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>
<spring-boot.repackage.skip>true</spring-boot.repackage.skip>
</properties>
</project>
@@ -0,0 +1,195 @@
= RESTful Notes API Guide
Baeldung;
:doctype: book
:icons: font
:source-highlighter: highlightjs
:toc: left
:toclevels: 4
:sectlinks:
[[overview]]
= Overview
[[overview-http-verbs]]
== HTTP verbs
RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its
use of HTTP verbs.
|===
| Verb | Usage
| `GET`
| Used to retrieve a resource
| `POST`
| Used to create a new resource
| `PATCH`
| Used to update an existing resource, including partial updates
| `DELETE`
| Used to delete an existing resource
|===
RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its
use of HTTP status codes.
|===
| Status code | Usage
| `200 OK`
| The request completed successfully
| `201 Created`
| A new resource has been created successfully. The resource's URI is available from the response's
`Location` header
| `204 No Content`
| An update to an existing resource has been applied successfully
| `400 Bad Request`
| The request was malformed. The response body will include an error providing further information
| `404 Not Found`
| The requested resource did not exist
|===
[[overview-hypermedia]]
== Hypermedia
RESTful Notes uses hypermedia and resources include links to other resources in their
responses. Responses are in http://stateless.co/hal_specification.html[Hypertext Application
from resource to resource.
Language (HAL)] format. Links can be found beneath the `_links` key. Users of the API should
not create URIs themselves, instead they should use the above-described links to navigate
[[resources]]
= Resources
[[resources-index]]
== Index
The index provides the entry point into the service.
[[resources-index-access]]
=== Accessing the index
A `GET` request is used to access the index
==== Request structure
include::{snippets}/index-example/http-request.adoc[]
==== Example response
include::{snippets}/index-example/http-response.adoc[]
==== CURL request
include::{snippets}/index-example/curl-request.adoc[]
[[resources-index-links]]
==== Links
include::{snippets}/index-example/links.adoc[]
[[resources-CRUD]]
== CRUD REST Service
The CRUD provides the entry point into the service.
[[resources-crud-get]]
=== Accessing the crud GET
A `GET` request is used to access the CRUD read.
==== Request structure
include::{snippets}/crud-get-example/http-request.adoc[]
==== Example response
include::{snippets}/crud-get-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-get-example/curl-request.adoc[]
[[resources-crud-post]]
=== Accessing the crud POST
A `POST` request is used to access the CRUD create.
==== Request structure
include::{snippets}/crud-create-example/http-request.adoc[]
==== Example response
include::{snippets}/crud-create-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-create-example/curl-request.adoc[]
[[resources-crud-delete]]
=== Accessing the crud DELETE
A `DELETE` request is used to access the CRUD delete.
==== Request structure
include::{snippets}/crud-delete-example/http-request.adoc[]
==== Path Parameters
include::{snippets}/crud-delete-example/path-parameters.adoc[]
==== Example response
include::{snippets}/crud-delete-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-delete-example/curl-request.adoc[]
[[resources-crud-patch]]
=== Accessing the crud PATCH
A `PATCH` request is used to access the CRUD update.
==== Request structure
include::{snippets}/crud-patch-example/http-request.adoc[]
==== Example response
include::{snippets}/crud-patch-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-patch-example/curl-request.adoc[]
[[resources-crud-put]]
=== Accessing the crud PUT
A `PUT` request is used to access the CRUD update.
==== Request structure
include::{snippets}/crud-put-example/http-request.adoc[]
==== Example response
include::{snippets}/crud-put-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-put-example/curl-request.adoc[]
@@ -0,0 +1,12 @@
package com.baeldung.queryparamdoc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,5 @@
package com.baeldung.queryparamdoc;
public class Book {
}
@@ -0,0 +1,23 @@
package com.baeldung.queryparamdoc;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<Book> getBooks(@RequestParam(name = "page") Integer page) {
return service.getBooks(page);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.queryparamdoc;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class BookService {
@SuppressWarnings("unused")
public List<Book> getBooks(Integer page) {
return new ArrayList<>();
}
}
@@ -0,0 +1,61 @@
package com.baeldung.restdocs;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import java.util.ArrayList;
import java.util.List;
import jakarta.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/crud")
public class CRUDController {
@GetMapping
public List<CrudInput> read(@RequestBody @Valid CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<>();
returnList.add(crudInput);
return returnList;
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public HttpHeaders save(@RequestBody @Valid CrudInput crudInput) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getId()).toUri());
return httpHeaders;
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
HttpHeaders delete(@PathVariable("id") long id) {
return new HttpHeaders();
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
}
@PatchMapping("/{id}")
public List<CrudInput> patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<>();
crudInput.setId(id);
returnList.add(crudInput);
return returnList;
}
}
@@ -0,0 +1,66 @@
package com.baeldung.restdocs;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CrudInput {
@NotNull
private long id;
@NotBlank
private String title;
private String body;
private List<URI> tagUris;
@JsonCreator
public CrudInput(@JsonProperty("id") long id, @JsonProperty("title") String title, @JsonProperty("body") String body, @JsonProperty("tags") List<URI> tagUris) {
this.id=id;
this.title = title;
this.body = body;
this.tagUris = tagUris == null ? Collections.<URI> emptyList() : tagUris;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setBody(String body) {
this.body = body;
}
public void setTagUris(List<URI> tagUris) {
this.tagUris = tagUris;
}
@JsonProperty("tags")
public List<URI> getTagUris() {
return this.tagUris;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.restdocs;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
@RestController
@RequestMapping("/")
public class IndexController {
static class CustomRepresentationModel extends RepresentationModel<CustomRepresentationModel> {
public CustomRepresentationModel(Link initialLink) {
super(initialLink);
}
}
@GetMapping
public CustomRepresentationModel index() {
return new CustomRepresentationModel(linkTo(CRUDController.class).withRel("crud"));
}
}
@@ -0,0 +1,13 @@
package com.baeldung.restdocs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class SpringRestDocsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRestDocsApplication.class, args);
}
}
@@ -0,0 +1,55 @@
package com.baeldung.queryparamdoc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
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.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.queryParameters;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
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.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
@WebMvcTest(controllers = {BookController.class, BookService.class},
excludeAutoConfiguration = SecurityAutoConfiguration.class)
class BookControllerMvcIntegrationTest {
@Autowired
private MockMvc mockMvc;
@BeforeEach
public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
this.mockMvc = webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentation))
.alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.build();
}
@Test
void smokeTest() {
assertThat(mockMvc).isNotNull();
}
@Test
void givenEndpoint_whenSendGetRequest_thenSuccessfulResponse() throws Exception {
mockMvc.perform(get("/books?page=2"))
.andExpect(status().isOk())
.andDo(document("books",
queryParameters(parameterWithName("page").description("The page to retrieve"))));
}
}
@@ -0,0 +1,61 @@
package com.baeldung.queryparamdoc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.queryParameters;
import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document;
import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration;
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.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.reactive.server.WebTestClient;
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
@WebFluxTest
class BookControllerReactiveIntegrationTest {
@Autowired
private WebTestClient webTestClient;
@BeforeEach
public void setUp(ApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
this.webTestClient = WebTestClient.bindToApplicationContext(webApplicationContext)
.configureClient()
.filter(documentationConfiguration(restDocumentation))
.build();
}
@Test
void smokeTest() {
assertThat(webTestClient).isNotNull();
}
@Test
@WithMockUser
void givenEndpoint_whenSendGetRequest_thenSuccessfulResponse() {
webTestClient.get().uri("/books?page=2")
.exchange().expectStatus().isOk().expectBody()
.consumeWith(document("books",
queryParameters(parameterWithName("page").description("The page to retrieve"))));
}
@TestConfiguration
public static class TestConfig {
@Bean
BookService bookService() {
return new BookService();
}
}
}
@@ -0,0 +1,51 @@
package com.baeldung.queryparamdoc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.queryParameters;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.restdocs.restassured.RestAssuredRestDocumentation;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
@AutoConfigureWebMvc
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class BookControllerRestAssuredIntegrationTest {
private RequestSpecification spec;
@BeforeEach
void setUp(RestDocumentationContextProvider restDocumentation, @LocalServerPort int port) {
this.spec = new RequestSpecBuilder().addFilter(RestAssuredRestDocumentation.documentationConfiguration(restDocumentation))
.setPort(port)
.build();
}
@Test
void smokeTest() {
assertThat(spec).isNotNull();
}
@Test
@WithMockUser
void givenEndpoint_whenSendGetRequest_thenSuccessfulResponse() {
RestAssured.given(this.spec).filter(RestAssuredRestDocumentation.document("users", queryParameters(
parameterWithName("page").description("The page to retrieve"))))
.when().get("/books?page=2")
.then().assertThat().statusCode(is(200));
}
}
@@ -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() {
}
}