SlideShare a Scribd company logo
Test Driven
Documentation
with Spring Rest Docs
Tsypuk Roman
@tsypuk_r
tsypuk.conf@gmail.com
About me
• Sr Software engineer at Lohika, Altran Group
• G4 organizer of Lohika Java Community
• java8, spring, spring boot, microservices, security
• radio HAM, software defined radio
2
Agenda
• Age of Swagger
• Test Driven Documentation
• Spring Rest Docs under the hood
• Migration from Swagger to Spring Rest Docs
3
Age of Swagger
4IMG http://swagger.io
Demo
https://github.com/tsypuk/springrestdoc 5
URI-based documentation
6
@GetMapping(path	=	"/speakers/{id}")
public	ResponseEntity<SpeakerResource>	getSpeaker(@PathVariablelong	id)	{
return	speakerRepository.findOne(id)
.map(speaker	->	ResponseEntity.ok(new	SpeakerResource(speaker)))
.orElse(new	ResponseEntity(HttpStatus.NOT_FOUND));
}
RestController
7
@GetMapping(path	=	"/speakers/{id}")
public	ResponseEntity<SpeakerResource>	getSpeaker(@PathVariablelong	id)	{
return	speakerRepository.findOne(id)
.map(speaker	->	ResponseEntity.ok(new	SpeakerResource(speaker)))
.orElse(new	ResponseEntity(HttpStatus.NOT_FOUND));
}
RestController
1
2
3
4
5
6
8
@ApiOperation(
value	=	"Find	speaker	by	ID",
notes	=	"For	valid	response	try	integer	IDs	with	value	1	...	999.",
response	=	SpeakerResource.class)
@ApiResponses(value	 =	{
@ApiResponse(code	 =	200,	message	=	"Successful	retrieve	the	speaker.",	response	=	SpeakerResource.class),
@ApiResponse(code	 =	400,	message	=	"Invalid	ID	supplied"),
@ApiResponse(code	 =	404,	message	=	"Speaker	not	found"),
@ApiResponse(code	 =	500,	message	=	"Internal	server	error.")})
@GetMapping(value	 =	"/{id}")
public	ResponseEntity<SpeakerResource>	 getSpeaker(
@ApiParam(value	=	"ID	of	speaker	that	needs	to	be	fetched",
allowableValues =	"range[1,999]",
required	=	true)
@PathVariable long	id)	{
return	speakerRepository.findOne(id)
.map(speaker	->	ResponseEntity.ok(new	SpeakerResource(speaker)))
.orElse(new	ResponseEntity(HttpStatus.NOT_FOUND));
}
Swagger Documented Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 10
Swagger Documented Models
1
2
3
4
5
6
7
8
…
@ApiModel(value	 =	"Speaker	Resource",	
description	=	"Speaker	detailed	description.")
public	class	SpeakerResource extends	ResourceSupport {
@ApiModelProperty(value	 =	"Name	of	the	Speaker	in	full	format.",
example	=	"Roman	Tsypuk",
dataType =	"java.lang.String",
required	=	true)
private	String	name;
11
/speakers/{speakerId}:
put:
tags:
- speaker
summary:	Updates	a	speaker	with	new	data
description:	""
operationId:	updateSpeaker
consumes:
- application/json
produces:
- application/json
parameters:
- in:	path
name:	speakerId
description:	ID	of	speaker	that	needs	to	be	updated
required:	true
type:	string
- in:	jsonData
name:	name
description:	Updated	name	of	the	speaker
required:	true
type:	string
- in:	jsonData
name:	company
description:	Updated	company	of	the	speaker
required:	false
type:	string
responses:
"405":
description:	Validation	exception
"404":
description:	Speaker	not	found
"400":
description:	Invalid	ID	supplied
"201":
description:	successful	operation
schema:
type:	array
items:
$ref:	"#/definitions/Speaker"
security:
- service_auth:
- write_speakers
- read_speakers
definitions
Speaker:
description:	Speaker	resource
required:
- name
- photoUrls
properties:
id:
type:	integer
format:	int64
topics:
type:	array
items:
$ref:	"#/definitions/Topic"
name:
type:	string
example:	Josh	Long
company:
type:	string
example:	Pivotal
status:
type:	string
description:	I	love	Spring
Swagger specification yaml file
12
Bottom-up (code-first)
io.swagger.annotations
Top-down (contract-first)
swagger.(yaml/json)
Tightly coupled code
with annotations
Swagger Approaches
13
Hypermedia Support
13
Level	0:	XML	RPC/Remoting
Singular	service	endpoint	 for	everything
Level	1:
Multiple	resources
Level	2:
Proper	use	of	HTTP	verbs
Level	3	HATEOAS:
Discoverability,	Hypermedia	controls
Swagger	2.0
https://martinfowler.com/articles/richardsonMaturityModel.html
Richardson Maturity Model
14
Level	0:	XML	RPC/Remoting
Singular	service	endpoint	 for	everything
Level	1:
Multiple	resources
Level	2:
Proper	use	of	HTTP	verbs
Level	3	HATEOAS:
Discoverability,	Hypermedia	controls
Swagger	2.0
Hypermedia is not supported in swagger 2.0
15
Level	0:	XML	RPC/Remoting
Singular	service	endpoint	 for	everything
Level	1:
Multiple	resources
Level	2:
Proper	use	of	HTTP	verbs
Level	3	HATEOAS:
Discoverability,	Hypermedia	controls
Swagger	2.0
OpenAPI3.0
OpenAPI 3.0 is comming
16
• Depends on the framework implementation details
• Specification is only machine-readable
• The format is not easy to use
• HATEOAS links are not supported (swagger 2.0)
• Annotations
• Documentation can be outdated
Swagger Problems
17
Spring Rest Docs
IMG http://spring.io 18
Spring Rest Docs
• Documentation is built from tests
• Clean code
• Documentation is part of a regular dev cycle
• Immediate reaction to API changes
• HATEOAS
19
Refactor
GREEN
RED
https://martinfowler.com/bliki/TestDrivenDevelopment.html
Classical Test Driven Development
20
Document
GREEN
Refactor
GREEN
RED
Spring Rest Docs Test Driven Documentation
21
Supports Integrated with
22
Spring Rest Docs
How does it work?
23
ResultActions actions	=	mockMvc.perform(get("/speakers/{id}",	SPEAKER_ID))
.andDo(print());
actions.andExpect(status().isOk())
.andExpect(jsonPath("$.name",	is("Roman	Tsypuk")))
.andExpect(jsonPath("$.company",	is("Lohika")));
MockMvc Test
ResultMatcher
24
ResultActions actions	=	mockMvc.perform(get("/speakers/{id}",	SPEAKER_ID))
.andDo(print());
actions.andExpect(status().isOk())
.andExpect(jsonPath("$.name",	is("Roman	Tsypuk")))
.andExpect(jsonPath("$.company",	is("Lohika")))
ResultHandler
MockMvc Key Players
.andDo( … )
25
Inside of ResultActions
ResultActions
MvcResultMockHttpServletRequest
encoding
content
contentType
contentLength
parameters
ServletResponse
headers
status
forwardUrl
includeUrl
errorMessage
HttpServletResponse
authType
cookie
header
method
pathInfo
HttpServletRequestServletRequest
attributes
charEncoding
content
contentType
parameters
serverPort
serverName
schema
async
MockHttpServletResponse
26
actions.andDo(document("{class-name}/{method-name}",
responseFields(
fieldWithPath("name").description("The	name	of	the	Speaker"),
fieldWithPath("company").description(”Speaker’s	company"),
fieldWithPath("status").description("Hope	only	good	:)"),
subsectionWithPath("_links").description("HATEOAS	links")),
links(halLinks(),
linkWithRel("self").description("Link	to	Speaker"),
linkWithRel("topics").description("Topics	of	the	Speaker"))));
ResultsHandler Registration
27
28
DocumentTests TemplateSnippets
Spring Rest Docs Flow
Live Coding
29https://github.com/tsypuk/springrestdoc
• Admonitions (tips, warnings, cautions, importants)
• Text formatting
• Lists (ordered, checklists)
• Code blocks highlighting
• Images/files
• Extensions
Asciidoc is Awesome
30
• NEO4J https://neo4j.com/docs/java-reference/3.1/#call-procedure
• O’Reilly books
• CouchDB http://guide.couchdb.org/draft/consistency.html
• Enterprise Web Development http://enterprisewebbook.com/
• Bintray https://bintray.com/docs/api/
• JBoss CDI Java EE http://docs.jboss.org/cdi/spec/1.1/cdi-spec.html
• SpringFox https://springfox.github.io/springfox/docs/current/
Asciidoc is Widely Used
31
Migration from
Swagger
Челове с	рюкзаком
Карта	с	маршрутом
IMG http://www.visolve.com/migration.php 32
Step 1: use swagger2markup (plug-in/dependency)
33
swagger2markup
paths
overview
definitions
security
Converted
From
Swagger
http://
Step 2: no TDDoc at this stage
34
DocumentTests TemplateSnippets
Converted
From
Swagger
Step 3: start using Spring Rest Docs
35
DocumentTests TemplateSnippets
Converted
From
Swagger
Spring
Rest Docs
Step 4: continue adding more sections
36
DocumentTests TemplateSnippets
Converted
From
Swagger
Spring
Rest Docs
Spring
Rest Docs
Step 5: all sections are under TDDoc control
37
DocumentTests TemplateSnippets
Spring
Rest Docs
Spring
Rest Docs
Spring
Rest Docs
Summary
38
Sources https://github.com/tsypuk/springrestdoc
39
Q&A
40
@tsypuk_r
tsypuk.conf@gmail.com
IMG http://www.melaclaro.com/
Links useful resources
• https://martinfowler.com/articles/richardsonMaturityModel.html
• https://www.tothepoint.company/blog/spring-rest-doc/
• https://opencredo.com/rest-api-tooling-review/
• https://speakerdeck.com/ankinson/documenting-restful-apis-webinar
• https://speakerdeck.com/ankinson/documenting-restful-apis-webinar
• https://projects.spring.io/spring-restdocs/
• https://causecode.com/blog/60/documenting-rest-api-grails-318-with-spring-rest-docs
• http://ditaa.sourceforge.net
• http://asciidoctor.org/docs/what-is-asciidoc/
41

More Related Content

PDF
Test Driven Documentation with Spring Rest Docs
PPTX
LinkRest at JeeConf 2017
PDF
Everything as a code
PDF
The JavaFX Ecosystem
PPTX
Java Libraries You Can’t Afford to Miss
PDF
トークンリフレッシュ処理を含むAPIClientのテスト #hakata_test_night
PDF
Making the Most of Your Gradle Build
PDF
ruxc0n 2012
Test Driven Documentation with Spring Rest Docs
LinkRest at JeeConf 2017
Everything as a code
The JavaFX Ecosystem
Java Libraries You Can’t Afford to Miss
トークンリフレッシュ処理を含むAPIClientのテスト #hakata_test_night
Making the Most of Your Gradle Build
ruxc0n 2012

What's hot (20)

PDF
Making the Most of Your Gradle Build
PDF
Regex Considered Harmful: Use Rosie Pattern Language Instead
PDF
Springを用いた社内ライブラリ開発
PDF
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
PPTX
The Gradle in Ratpack: Dissected
PDF
Managing user's data with Spring Session
PDF
Drools 6.0 (Red Hat Summit)
PDF
Journée DevOps : Des dashboards pour tous avec ElasticSearch, Logstash et Kibana
PPT
Logstash
PDF
Docker Logging and analysing with Elastic Stack
PDF
DAST в CI/CD, Ольга Свиридова
PDF
Java(ee) mongo db applications in the cloud
PDF
Altitude NY 2018: Programming the edge workshop
PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
PDF
Monitoring with Graylog - a modern approach to monitoring?
PDF
Retrofit
PDF
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
PDF
A Modest Introduction To Swift
PDF
Drools 6.0 (JudCon 2013)
PDF
Distributed Eventing in OSGi - Carsten Ziegeler
Making the Most of Your Gradle Build
Regex Considered Harmful: Use Rosie Pattern Language Instead
Springを用いた社内ライブラリ開発
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
The Gradle in Ratpack: Dissected
Managing user's data with Spring Session
Drools 6.0 (Red Hat Summit)
Journée DevOps : Des dashboards pour tous avec ElasticSearch, Logstash et Kibana
Logstash
Docker Logging and analysing with Elastic Stack
DAST в CI/CD, Ольга Свиридова
Java(ee) mongo db applications in the cloud
Altitude NY 2018: Programming the edge workshop
We Are All Testers Now: The Testing Pyramid and Front-End Development
Monitoring with Graylog - a modern approach to monitoring?
Retrofit
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
A Modest Introduction To Swift
Drools 6.0 (JudCon 2013)
Distributed Eventing in OSGi - Carsten Ziegeler
Ad

Similar to Test Driven Documentation with Spring Rest Docs JEEConf2017 (20)

PDF
Python & Django TTT
PDF
Test-Driven Documentation for your REST(ful) service
PDF
Software Supply Chains for DevOps @ InfoQ Live 2021
PDF
Annotation processing and code gen
PDF
2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...
PDF
Research software and Dataverse
PDF
GraalVM and MicroProfile - A Polyglot Microservices Solution
PDF
Jersey
PPTX
Make BDD great again
PDF
Phoenix + Reactで 社内システムを 密かに作ってる
PPTX
GraphQL - The new "Lingua Franca" for API-Development
KEY
DevQuiz 2011 の模範解答 Android編
PPTX
React inter3
PPTX
Fast Data Intelligence in the IoT - real-time data analytics with Spark
PPTX
RDF Validation in a Linked Data World - A vision beyond structural and value ...
PDF
High-level Programming Languages: Apache Pig and Pig Latin
PDF
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
PPTX
Improving code quality with Roslyn analyzers
PPTX
Webinar: Simplifying Persistence for Java and MongoDB
PDF
Everything-as-code – Polyglotte Entwicklung in der Praxis
Python & Django TTT
Test-Driven Documentation for your REST(ful) service
Software Supply Chains for DevOps @ InfoQ Live 2021
Annotation processing and code gen
2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...
Research software and Dataverse
GraalVM and MicroProfile - A Polyglot Microservices Solution
Jersey
Make BDD great again
Phoenix + Reactで 社内システムを 密かに作ってる
GraphQL - The new "Lingua Franca" for API-Development
DevQuiz 2011 の模範解答 Android編
React inter3
Fast Data Intelligence in the IoT - real-time data analytics with Spark
RDF Validation in a Linked Data World - A vision beyond structural and value ...
High-level Programming Languages: Apache Pig and Pig Latin
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
Improving code quality with Roslyn analyzers
Webinar: Simplifying Persistence for Java and MongoDB
Everything-as-code – Polyglotte Entwicklung in der Praxis
Ad

More from Roman Tsypuk (6)

PPTX
Amazon Alexa: How to talk with your Smart Home devices
PPTX
Voice control with Amazon Alexa(for pacemaker conf)
PDF
Web Security training for Lohika.
PDF
Effective Java. By materials of Josch Bloch's book
PDF
Java agents are watching your ByteCode
PDF
IoT. GPS in our cars.
Amazon Alexa: How to talk with your Smart Home devices
Voice control with Amazon Alexa(for pacemaker conf)
Web Security training for Lohika.
Effective Java. By materials of Josch Bloch's book
Java agents are watching your ByteCode
IoT. GPS in our cars.

Recently uploaded (20)

PDF
top salesforce developer skills in 2025.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
Transform Your Business with a Software ERP System
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Introduction to Artificial Intelligence
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Digital Strategies for Manufacturing Companies
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
System and Network Administraation Chapter 3
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
L1 - Introduction to python Backend.pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
top salesforce developer skills in 2025.pdf
Understanding Forklifts - TECH EHS Solution
Softaken Excel to vCard Converter Software.pdf
How to Choose the Right IT Partner for Your Business in Malaysia
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Transform Your Business with a Software ERP System
CHAPTER 2 - PM Management and IT Context
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PTS Company Brochure 2025 (1).pdf.......
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Introduction to Artificial Intelligence
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
How to Migrate SBCGlobal Email to Yahoo Easily
Digital Strategies for Manufacturing Companies
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
System and Network Administraation Chapter 3
Which alternative to Crystal Reports is best for small or large businesses.pdf
L1 - Introduction to python Backend.pptx
Design an Analysis of Algorithms II-SECS-1021-03

Test Driven Documentation with Spring Rest Docs JEEConf2017

Editor's Notes

  • #12: Screen X controller X methods