SlideShare a Scribd company logo
1 of 28
Testing Microservices
Types of Testing
API
Service
Persistence
Database
Client
Service
Stubs
External Service
Microservice
Microservice
Domain
Unit Test
Integration Test
Component Test
Contracts
Contracts
End-to-end Test
Test Pyramid
Exploratory
End to end
Component /
Contracts
Integration
Unit (Solitary / Sociable)
Manual
Selenium, Appium, Sikuli,
JBehave
Spring Cloud Contract, Pact,
Cucumber
Junit, SOAPUI
Junit, Nunit, Mockito, JMock,
Lambda Behave
Consumer Driven
Contracts
Testing Services
S1
S2 S3
S4
1. Deploy all Microservices and
perform end-to-end tests
Testing Approach
1. Simulates production
2. Real communication
1. Too cumbersome – deploy DB,
all services
2. Late feedback
3. Environment blocked
4. Very hard to debug
Testing Services
S1
2. Mocking other Microservices in
unit/integration tests
Testing Approach
1. Fast feedback
2. No infrastructure setup
1. Stubs might be different
than the real service
2. Tests will pass but the
application might fail in
production
What do we need?
Producer
•Define contract
•Verify that API implementation is per contract – server tests
•Publish stub versions to repo – changes visible to both sides
Consumer
•Mock producer based on stub definitions – client integration
tests
•ATDD – Acceptance TDD
Consumer Driven Contracts
Consumer
Producer Repository
Acceptance
Tests
Client Test
Integration Test
Spring Cloud Contract Verifier
Contract Definition Language (DSL)
• Definition either in groovy or pact format
Used to produce following resources
• JSON stub definitions
 Used by client side
 Test written by hand, test data provided by Spring
• Server tests
 Test generated by Spring
Build script – Consumer (task-webservice)
dependencies
• testCompile("org.springframework.security:spring-security-test")
• testCompile("org.springframework.cloud:spring-cloud-starter-
contract-stub-runner")
Client tests
Create integration test
• Annotations
@RunWith(SpringRunner.class) // 1
@SpringBootTest(webEnvironment = WebEnvironment.MOCK, properties = {
"spring.cloud.discovery.enabled=false",
"spring.cloud.config.enabled=false","stubrunner.idsToServiceIds.basic-comments-webservice-
stubs=comments-webservice" }). // 2
@Import(OAuth2ClientTestConfiguration.class). // 3
@AutoConfigureStubRunner(ids={"anilallewar:basic-comments-webservice-stubs:+:stubs:9083"},
workOffline=true) // 4
@DirtiesContext // 5
Client tests
Actual test
Fails for 2 reasons
• Call is secured though OAuth2 access token
• Stub definition not available
@Test
public void testGetCommentsForTask() {
CommentCollectionResource comments =
this.commentsService.getCommentsForTask(REQUEST_TASK_ID);
Assert.assertEquals(2, comments.getTaskComments().size());
Assert.assertTrue(comments.getTaskComments().get(0).getTaskId().equals(TEST_TASK_ID));
}
Mock OAuth2 token
Create SecurityContext holding the mock access token
• https://spring.io/blog/2014/05/07/preview-spring-security-test-
method-security#withsecuritycontext
Code
• https://github.com/anilallewar/microservices-basics-spring-
boot/tree/master/task-
webservice/src/test/java/com/anilallewar/microservices/task
Run tests
Once you have the MockOAuth2 token code
• Comment the @AutoConfigureStubRunner annotation
• Run the test with ./gradlew clean build
java.lang.AssertionError: expected:<2> but was:<1>
• Circuit breaker kicked in and provided default value
Uncomment @AutoConfigureStubRunner and run the test
• Error creating bean with name 'batchStubRunner'
Build script – Producer (comments-webservice)
buildscript
• project.ext
 springCloudContractVesrion = '1.1.1.RELEASE'
• dependencies
 classpath "org.springframework.cloud:spring-cloud-contract-gradle-
plugin:${project.springCloudContractVesrion}”
dependencies
• testCompile('org.springframework.cloud:spring-cloud-starter-
contract-verifier')
Build script – Producer (comments-webservice)
// Setup the package which contains base classes that the spring cloud contract test case would extend
contracts {
packageWithBaseClasses = 'com.anilallewar.microservices.comments.contracts'
}
clean.doFirst {
delete "~/.m2/repository/anilallewar/basic-comments-webservice"
delete "~/.m2/repository/anilallewar/basic-comments-webservice-stubs"
}
// Setup the artifact id with which the stubs jar would be published, the group id comes from the 'group' attribute defined earlier
publishing {
publications {
mavenJava(MavenPublication) {
artifactId jar.baseName
version jar.version
from components.java
}
stubs(MavenPublication) {
artifactId "${jar.baseName}-stubs"
version jar.version
artifact verifierStubsJar
}
}
}
Contract DSL
Src/test/resources/contracts
request {
method 'GET'
url $(consumer(regex('/comments/([0-9a-
zA-z]+)')), producer('/comments/task11'))
headers {
accept(applicationJson())
}
}
response {
status 200
body( [
[
"taskId": "task11",
"comment": "comment on task11",
"posted": $(consumer('2015-04-
23'),producer(execute('convertTimeValueToDate($it)')))
]]
)
headers {
contentType('application/json')
}
}
Abstract Base Class
Generated test extends the defined base class
Since the package for base classes is defined
as com.anilallewar.microservices.comments.contracts and
the contract is defined under the task/comments folder
under test/resources/contracts, the base class name is
TaskCommentsBase
Add @Ignore annotation – not a test class
Abstract base class
Inject a WebApplicationContext so that Spring dependency is
initialized correctly.
Annotations
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { CommentsApplication.class }, webEnvironment
= WebEnvironment.MOCK, properties = {
"spring.cloud.discovery.enabled=false", "spring.cloud.config.enabled=false"
})
Run tests
 Run the test with ./gradlew clean build
•This will generate the server tests under /comments-
webservice/build/generated-test-
sources/contracts/org/springframework/cloud/contract/verifier
/tests
 Publish the contract stub using ./gradlew
publishToMavenLocal
 Once the contract is published, go to the task-webservice
folder and run ./gradlew clean build
•This time around the test should pass
Distributed Tracing
Sleuth & Zipkin
Sleuth
• Attaches unique id to request as it passes through enabled services
• Logs can be mined using aggregation tools like ELK (ElasticSearch,
Logstash and Kibana)
Zipkin
• Distributed tracing system
• Gathers timing data across Microservices – collection and lookup
Dependencies
Create a new project by visiting https://start.spring.io/
• Gradle project –> with Java and Spring Boot 1.5.4
• Group -> com.<name>.microservices
• Artifact -> tracing
• Dependencies -> Zipkin UI, Zipkin Client
Additional dependency
• compile('io.zipkin.java:zipkin-server')
Run ./gradlew clean build eclipse
Code changes
Application.properties
• server.port=9411
Alternatively you can add configuration on the centralized
configuration server
Add @EnableZipkinServer annotation on the Spring boot
application class
Add Zipkin client properties
Check below properties exists in configuration files for “api-
gateway”, “comments-webservice”, “task-webservice” and
“user-webservice”
spring:
zipkin:
baseUrl: http://localhost:9411/
sleuth:
sampler:
percentage: 1.0
sample:
zipkin:
enabled: true
View Traces
Run all the Microservices and other servers (zipkin server,
web-portal etc)
Hit http://localhost:9411/ (Zipkin base url)
UI
• Find specific trace and timing information
• Service dependency graph
Trace id is added to logs – enables distributed log analysis
Sample Trace
Contact Me
anilallewar@yahoo.co.in
https://www.linkedin.com/in/anilallewar
https://github.com/anilallewar
http://www.slideshare.net/anilallewar
@anilallewar

More Related Content

What's hot

What's hot (20)

Microservices Architecture
Microservices ArchitectureMicroservices Architecture
Microservices Architecture
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
 
Designing APIs with OpenAPI Spec
Designing APIs with OpenAPI SpecDesigning APIs with OpenAPI Spec
Designing APIs with OpenAPI Spec
 
Modern CI/CD Pipeline Using Azure DevOps
Modern CI/CD Pipeline Using Azure DevOpsModern CI/CD Pipeline Using Azure DevOps
Modern CI/CD Pipeline Using Azure DevOps
 
Microservices testing strategy-v2
Microservices testing strategy-v2Microservices testing strategy-v2
Microservices testing strategy-v2
 
Why Microservices
Why MicroservicesWhy Microservices
Why Microservices
 
An introduction to Microservices
An introduction to MicroservicesAn introduction to Microservices
An introduction to Microservices
 
Event Sourcing & CQRS, Kafka, Rabbit MQ
Event Sourcing & CQRS, Kafka, Rabbit MQEvent Sourcing & CQRS, Kafka, Rabbit MQ
Event Sourcing & CQRS, Kafka, Rabbit MQ
 
Microservices Architecture - Bangkok 2018
Microservices Architecture - Bangkok 2018Microservices Architecture - Bangkok 2018
Microservices Architecture - Bangkok 2018
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
Microservices Security
Microservices SecurityMicroservices Security
Microservices Security
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
 
Introducing OpenAPI Version 3.1
Introducing OpenAPI Version 3.1Introducing OpenAPI Version 3.1
Introducing OpenAPI Version 3.1
 
Microservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native AppsMicroservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native Apps
 
Microservices Architecture Part 2 Event Sourcing and Saga
Microservices Architecture Part 2 Event Sourcing and SagaMicroservices Architecture Part 2 Event Sourcing and Saga
Microservices Architecture Part 2 Event Sourcing and Saga
 
OpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of SwaggerOpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of Swagger
 
Microservices architecture
Microservices architectureMicroservices architecture
Microservices architecture
 
Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architecture
 
Microservices, DevOps & SRE
Microservices, DevOps & SREMicroservices, DevOps & SRE
Microservices, DevOps & SRE
 
CI/CD Pipeline Security: Advanced Continuous Delivery Best Practices: Securit...
CI/CD Pipeline Security: Advanced Continuous Delivery Best Practices: Securit...CI/CD Pipeline Security: Advanced Continuous Delivery Best Practices: Securit...
CI/CD Pipeline Security: Advanced Continuous Delivery Best Practices: Securit...
 

Similar to Testing Microservices

谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
drewz lin
 

Similar to Testing Microservices (20)

Spring boot microservice metrics monitoring
Spring boot   microservice metrics monitoringSpring boot   microservice metrics monitoring
Spring boot microservice metrics monitoring
 
Spring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics MonitoringSpring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics Monitoring
 
Zure Azure PaaS Zero to Hero - DevOps training day
Zure Azure PaaS Zero to Hero - DevOps training dayZure Azure PaaS Zero to Hero - DevOps training day
Zure Azure PaaS Zero to Hero - DevOps training day
 
Testing Spring MVC and REST Web Applications
Testing Spring MVC and REST Web ApplicationsTesting Spring MVC and REST Web Applications
Testing Spring MVC and REST Web Applications
 
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustAndroid Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
 
Azure serverless architectures
Azure serverless architecturesAzure serverless architectures
Azure serverless architectures
 
Scale and Load Testing of Micro-Service
Scale and Load Testing of Micro-ServiceScale and Load Testing of Micro-Service
Scale and Load Testing of Micro-Service
 
Session 41 - Struts 2 Introduction
Session 41 - Struts 2 IntroductionSession 41 - Struts 2 Introduction
Session 41 - Struts 2 Introduction
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
Kirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationKirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for Automatization
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
MuleSoft Kochi Meetup #3– Integration with Web Sockets
 MuleSoft Kochi Meetup #3– Integration with Web Sockets MuleSoft Kochi Meetup #3– Integration with Web Sockets
MuleSoft Kochi Meetup #3– Integration with Web Sockets
 
Continuous Delivery: How RightScale Releases Weekly
Continuous Delivery: How RightScale Releases WeeklyContinuous Delivery: How RightScale Releases Weekly
Continuous Delivery: How RightScale Releases Weekly
 
Cloud-based Test Microservices JavaOne 2014
Cloud-based Test Microservices JavaOne 2014Cloud-based Test Microservices JavaOne 2014
Cloud-based Test Microservices JavaOne 2014
 
Come Sail Away With Me (you guys): Node.js MVC Web API's Using Sails.js
Come Sail Away With Me (you guys): Node.js MVC Web API's Using Sails.jsCome Sail Away With Me (you guys): Node.js MVC Web API's Using Sails.js
Come Sail Away With Me (you guys): Node.js MVC Web API's Using Sails.js
 
Spring 1 day program
Spring 1 day programSpring 1 day program
Spring 1 day program
 
Advanced Continuous Delivery on AWS
Advanced Continuous Delivery on AWSAdvanced Continuous Delivery on AWS
Advanced Continuous Delivery on AWS
 
DevOps with Elastic Beanstalk - TCCC-2014
DevOps with Elastic Beanstalk - TCCC-2014DevOps with Elastic Beanstalk - TCCC-2014
DevOps with Elastic Beanstalk - TCCC-2014
 

Recently uploaded

Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Recently uploaded (20)

OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 

Testing Microservices

  • 2. Types of Testing API Service Persistence Database Client Service Stubs External Service Microservice Microservice Domain Unit Test Integration Test Component Test Contracts Contracts End-to-end Test
  • 3. Test Pyramid Exploratory End to end Component / Contracts Integration Unit (Solitary / Sociable) Manual Selenium, Appium, Sikuli, JBehave Spring Cloud Contract, Pact, Cucumber Junit, SOAPUI Junit, Nunit, Mockito, JMock, Lambda Behave
  • 5. Testing Services S1 S2 S3 S4 1. Deploy all Microservices and perform end-to-end tests Testing Approach 1. Simulates production 2. Real communication 1. Too cumbersome – deploy DB, all services 2. Late feedback 3. Environment blocked 4. Very hard to debug
  • 6. Testing Services S1 2. Mocking other Microservices in unit/integration tests Testing Approach 1. Fast feedback 2. No infrastructure setup 1. Stubs might be different than the real service 2. Tests will pass but the application might fail in production
  • 7. What do we need? Producer •Define contract •Verify that API implementation is per contract – server tests •Publish stub versions to repo – changes visible to both sides Consumer •Mock producer based on stub definitions – client integration tests •ATDD – Acceptance TDD
  • 8. Consumer Driven Contracts Consumer Producer Repository Acceptance Tests Client Test Integration Test
  • 9. Spring Cloud Contract Verifier Contract Definition Language (DSL) • Definition either in groovy or pact format Used to produce following resources • JSON stub definitions  Used by client side  Test written by hand, test data provided by Spring • Server tests  Test generated by Spring
  • 10. Build script – Consumer (task-webservice) dependencies • testCompile("org.springframework.security:spring-security-test") • testCompile("org.springframework.cloud:spring-cloud-starter- contract-stub-runner")
  • 11. Client tests Create integration test • Annotations @RunWith(SpringRunner.class) // 1 @SpringBootTest(webEnvironment = WebEnvironment.MOCK, properties = { "spring.cloud.discovery.enabled=false", "spring.cloud.config.enabled=false","stubrunner.idsToServiceIds.basic-comments-webservice- stubs=comments-webservice" }). // 2 @Import(OAuth2ClientTestConfiguration.class). // 3 @AutoConfigureStubRunner(ids={"anilallewar:basic-comments-webservice-stubs:+:stubs:9083"}, workOffline=true) // 4 @DirtiesContext // 5
  • 12. Client tests Actual test Fails for 2 reasons • Call is secured though OAuth2 access token • Stub definition not available @Test public void testGetCommentsForTask() { CommentCollectionResource comments = this.commentsService.getCommentsForTask(REQUEST_TASK_ID); Assert.assertEquals(2, comments.getTaskComments().size()); Assert.assertTrue(comments.getTaskComments().get(0).getTaskId().equals(TEST_TASK_ID)); }
  • 13. Mock OAuth2 token Create SecurityContext holding the mock access token • https://spring.io/blog/2014/05/07/preview-spring-security-test- method-security#withsecuritycontext Code • https://github.com/anilallewar/microservices-basics-spring- boot/tree/master/task- webservice/src/test/java/com/anilallewar/microservices/task
  • 14. Run tests Once you have the MockOAuth2 token code • Comment the @AutoConfigureStubRunner annotation • Run the test with ./gradlew clean build java.lang.AssertionError: expected:<2> but was:<1> • Circuit breaker kicked in and provided default value Uncomment @AutoConfigureStubRunner and run the test • Error creating bean with name 'batchStubRunner'
  • 15. Build script – Producer (comments-webservice) buildscript • project.ext  springCloudContractVesrion = '1.1.1.RELEASE' • dependencies  classpath "org.springframework.cloud:spring-cloud-contract-gradle- plugin:${project.springCloudContractVesrion}” dependencies • testCompile('org.springframework.cloud:spring-cloud-starter- contract-verifier')
  • 16. Build script – Producer (comments-webservice) // Setup the package which contains base classes that the spring cloud contract test case would extend contracts { packageWithBaseClasses = 'com.anilallewar.microservices.comments.contracts' } clean.doFirst { delete "~/.m2/repository/anilallewar/basic-comments-webservice" delete "~/.m2/repository/anilallewar/basic-comments-webservice-stubs" } // Setup the artifact id with which the stubs jar would be published, the group id comes from the 'group' attribute defined earlier publishing { publications { mavenJava(MavenPublication) { artifactId jar.baseName version jar.version from components.java } stubs(MavenPublication) { artifactId "${jar.baseName}-stubs" version jar.version artifact verifierStubsJar } } }
  • 17. Contract DSL Src/test/resources/contracts request { method 'GET' url $(consumer(regex('/comments/([0-9a- zA-z]+)')), producer('/comments/task11')) headers { accept(applicationJson()) } } response { status 200 body( [ [ "taskId": "task11", "comment": "comment on task11", "posted": $(consumer('2015-04- 23'),producer(execute('convertTimeValueToDate($it)'))) ]] ) headers { contentType('application/json') } }
  • 18. Abstract Base Class Generated test extends the defined base class Since the package for base classes is defined as com.anilallewar.microservices.comments.contracts and the contract is defined under the task/comments folder under test/resources/contracts, the base class name is TaskCommentsBase Add @Ignore annotation – not a test class
  • 19. Abstract base class Inject a WebApplicationContext so that Spring dependency is initialized correctly. Annotations @RunWith(SpringRunner.class) @SpringBootTest(classes = { CommentsApplication.class }, webEnvironment = WebEnvironment.MOCK, properties = { "spring.cloud.discovery.enabled=false", "spring.cloud.config.enabled=false" })
  • 20. Run tests  Run the test with ./gradlew clean build •This will generate the server tests under /comments- webservice/build/generated-test- sources/contracts/org/springframework/cloud/contract/verifier /tests  Publish the contract stub using ./gradlew publishToMavenLocal  Once the contract is published, go to the task-webservice folder and run ./gradlew clean build •This time around the test should pass
  • 22. Sleuth & Zipkin Sleuth • Attaches unique id to request as it passes through enabled services • Logs can be mined using aggregation tools like ELK (ElasticSearch, Logstash and Kibana) Zipkin • Distributed tracing system • Gathers timing data across Microservices – collection and lookup
  • 23. Dependencies Create a new project by visiting https://start.spring.io/ • Gradle project –> with Java and Spring Boot 1.5.4 • Group -> com.<name>.microservices • Artifact -> tracing • Dependencies -> Zipkin UI, Zipkin Client Additional dependency • compile('io.zipkin.java:zipkin-server') Run ./gradlew clean build eclipse
  • 24. Code changes Application.properties • server.port=9411 Alternatively you can add configuration on the centralized configuration server Add @EnableZipkinServer annotation on the Spring boot application class
  • 25. Add Zipkin client properties Check below properties exists in configuration files for “api- gateway”, “comments-webservice”, “task-webservice” and “user-webservice” spring: zipkin: baseUrl: http://localhost:9411/ sleuth: sampler: percentage: 1.0 sample: zipkin: enabled: true
  • 26. View Traces Run all the Microservices and other servers (zipkin server, web-portal etc) Hit http://localhost:9411/ (Zipkin base url) UI • Find specific trace and timing information • Service dependency graph Trace id is added to logs – enables distributed log analysis

Editor's Notes

  1. Run the test with the SpringRunner class instead of standard Junit runner Properties injected into spring boot environment Disable discovery and configuration from external sources Map the stubs present in the “basic-comments-webservice-stubs” repo to the “comments-webservice” service Setup OAuth2 client configuration Configure the stubs defined in the “basic-comments-webservice-stubs” jar file that is under the “anilallewar” group under any version and run the stub server on port 9083 Remove the Spring application context after the test