SlideShare a Scribd company logo
No API? No problem!
API mocking with WireMock
An open source workshop by …
Originally created by Bas Dijkstra – bas@ontestautomation.com – https://www.ontestautomation.com
What are we going to do?
_Stubbing, mocking and service virtualization
_WireMock
_Exercises, examples, …
Preparation
_Install JDK (Java 17 or newer)
_Install IntelliJ IDEA (or any other IDE)
_Download or clone project
_Import Maven project in IDE
Section 0:
An introduction to
service virtualization
Problems in test environments
_Systems are constructed out of of many different
components
_Not all of these components are always available
for testing
_Parallel development
_No control over test data
_Fees required for using third party components
_…
Problems in test environments
System under test
Mainframe
SaaS
dependency
Backend
system
Mobile app
No suitable test data Limited access
Under development Access fees
Simulation during test
execution
_Simulate dependency behaviour
_Regain full control over test environment
_Available on demand
_Full control over test data (edge cases!)
_No third party component usage fees
_…
Problems in test environments
System under test
Mainframe
SaaS
dependency
Backend
system
Mobile app
No suitable test data Limited access
Under development Access fees
Simulation in test environments
System under test
Virtualized
mainframe
Virtualized
SaaS
dependency
Virtualized
backend
system
Virtualized
mobile app
Unrestricted access
Unrestricted access
Unrestricted access
Unrestricted access
API
consumer
API
provider
request
response
System System
API
consumer
API
provider
request
response
System
Simulating APIs
for more
efficient testing
and automation Simulation
Our system under test
_ParaBank
_The world’s least safe
online bank
_Request Loan process
_Loan application is processed by 3rd party loan
provider component
Loan
Processor
service
A
P
I
ParaBank
middleware
A
P
I
Frontend
/
API client
3rd
party development
team
ParaBank development team
Simulated
Loan
Processor
service
A
P
I
ParaBank
middleware
A
P
I
Frontend
/
API client
WireMock
ParaBank development team
What might we
want to simulate?
Start testing against features under development
Delays, fault status codes, malformatted responses, …
…
Easy setup of state for edge cases
Section 1:
Getting started with
WireMock
WireMock
_https://wiremock.org
_Java
_ports and adapters are available for many other languages
_HTTP mock server
_only supports HTTP(S)
_Open source
Install WireMock
_Maven
<dependency> <groupId>org.wiremock</
groupId>
<artifactId>wiremock</artifactId>
<version>3.3.1</version>
<scope>test</test>
</dependency>
Starting WireMock (JUnit 4)
_Via JUnit 4 @Rule
_Without using JUnit 4 @Rule
Starting WireMock (JUnit 5)
_Uses the JUnit 5 Jupiter extension mechanism
_Via @WireMockTest class annotation (basic configuration)
_Programmatically using @RegisterExtension (full control)
Starting WireMock (standalone)
_Useful for exploratory testing purposes
_Allows you to share WireMock instances between
teams
_Long-running instances
_Download the .jar first
java -jar wiremock-standalone-3.3.1.jar --port 9876
Configure responses
_In (Java) code
_Using JSON mapping files
An example mock defined in Java
Some useful WireMock features
_Verification
_ Verify that certain requests are sent by application under test
_Record and playback
_ Generate mocks based on request-response pairs (traffic)
_Fault simulation
_…
_Full documentation at https://wiremock.org/docs/
Now it’s your turn!
_exercises > WireMockExercises1Test.java
_Create a couple of basic mocks
_ Implement the responses as described in the comments
_Verify your solution by running the tests in the same
file
_Answers are in answers > WireMockAnswers1Test.java
_Examples are in examples > WireMockExamplesTest.java
Section 2:
Request matching
strategies and fault
simulation
Request matching
_Send a response only when certain properties in
the request are matched
_Options for request matching:
_URL
_HTTP method
_Query parameters
_Headers
_Request body elements
_…
Example: URL matching
_Other URL options:
_urlPathEqualTo (matches only path, no query parameters)
_urlMatching (using regular expressions)
_urlPathMatching (using regular expressions)
Example: header matching
_absent(): check that header is not in request
Example: using logical AND and OR
_‘somevalue’ is matched
_‘bananasomevaluebanana’ is matched
_‘banana’ is not matched (does not contain ‘somevalue’)
_‘123somevalue’ is not matched (contains numeric characters)
Some more examples…
Same behaviour as the previous example,
using a slightly different syntax
Matching on request body elements
Matching only those request bodies that have a root level element
fruits with a child element banana with value 2
{“fruits”: {“banana”: “2”, “apple”: “5”} }  MATCH
{“fruits”: {“apple”: “5”} }  NO MATCH
{“fruits”: {“banana”: “3”, “apple”: “5”} }  NO MATCH
Matching using date/time properties
Matching all dates after
midnight of July 1, 2021
Matching all dates at least 1
month before the current date
Other matching strategies
_Authentication (Basic, OAuth(2))
_Query parameters
_Multipart/form-data
_You can write your own matching logic, too
Fault simulation
_Extend test coverage by simulating faults
_Often hard to do in real systems
_Easy to do using stubs or mocks
_Used to test the exception handling of your
application under test
Example: HTTP status code
_Some often used HTTP status codes:
Consumer error Provider error
403 (Forbidden) 500 (Internal server error)
404 (Not found) 503 (Service unavailable)
Example: timeout
_Random delay can also be used
_Uniform, lognormal distribution
_Can be configured on a per-stub basis as well as
globally
Example: bad response
_HTTP status code 200, but garbage in response body
_Other options:
_RANDOM_DATA_THEN_CLOSE (as above, without HTTP 200)
_EMPTY_RESPONSE (does what it says on the tin)
_CONNECTION_RESET_BY_PEER (close connection, no response)
Now it’s your turn!
_exercises > WireMockExercises2Test.java
_Practice fault simulation and different request matching
strategies
_ Implement the responses as described in the comments
_Verify your solution by running the tests in the same
file
_Answers are in answers > WireMockAnswers2Test.java
_Examples are in examples > WireMockExamplesTest.java
Section 3:
Creating stateful mocks
Statefulness
_Sometimes, you want to simulate stateful
behaviour
_Shopping cart (empty / containing items)
_Database (data present / not present)
_Order in which requests arrive is significant
Stateful mocks in WireMock
_Supported through the concept of a Scenario
_Essentially a finite state machine (FSM)
_States and state transitions
_Combination of current state and incoming
request determines the response being sent
_Before now, it was only the incoming request
Stateful mocks: an example
Responses are grouped
by scenario name
Response depends on
both the incoming
request as well as
the current state
The initial state
should always be
Scenario.STARTED
Incoming requests can
trigger state
transitions
State names other
than Scenario.STARTED
are yours to define
Now it’s your turn!
_exercises > WireMockExercises3Test.java
_Create a stateful mock that exerts the described
behaviour
_ Implement the responses as described in the comments
_Verify your solution by running the tests in the same
file
_Answers are in answers > WireMockAnswers3Test.java
_Examples are in examples > WireMockExamplesTest.java
Section 4:
Response templating
Response templating
_Often, you want to reuse elements from the request
in the response
_Request ID header
_Unique body elements (client ID, etc.)
_Cookie values
_WireMock supports this through response templating
Setup response templating (JUnit 4)
_In code: through the JUnit @Rule
_Global == false: response templating transformer
has to be enabled for individual stubs
Setup response templating (JUnit 5)
_In code: through the JUnit @RegisterExtension
_Argument == false: response templating has to be
enabled for individual stubs
Enable/apply response templating
_This template reads the HTTP request method
(GET/POST/PUT/…) using {{request.method}} and
returns it as the response body
This call to withTransformers() is only necessary when
response templating isn’t activated globally
One thing to keep in mind…
… we need to explicitly assign our stub definition to that
instance here, or else the stub definition will not be picked up!
Because we’re explicitly initializing
a WireMock instance here…
Request attributes
_Many different request attributes available for use
_ request.method : HTTP method (example)
_ request.pathSegments.[<n>] : nth
path segment
_ request.headers.<key> : header with name key
_ …
_All available attributes listed at
https://wiremock.org/docs/response-templating/
Request attributes (cont’d)
_Extracting and reusing body elements
_In case of a JSON request body:
{{jsonPath request.body ‘$.path.to.element’}}
_In case of an XML request body:
{{xPath request.body ‘/path/to/element/text()’}}
JSON extraction example
_When sent this JSON
request body:
_This stub returns a response with body “Pillars of
the Earth”:
Again, this call to withTransformers() is only necessary
when response templating isn’t activated globally
Now it’s your turn!
_exercises > WireMockExercises4Test.java
_Create mocks that use response templating
_ Implement the responses as described in the comments
_Verify your solution by running the tests in the same
file
_Answers are in answers > WireMockAnswers4Test.java
_Examples are in examples > WireMockExamplesTest.java
Section 5:
Verification
Verifying incoming requests
_Apart from returning responses, you might also
want to verify that incoming requests have certain
properties
_Fail a test if these verifications aren’t met
_You can do this with WireMock in a way very
similar to mocking frameworks for unit tests
(e.g., Mockito for Java)
Verifying
incoming
requests
Given this simple
‘hello world’ stub
When we have this
test that should
invoke that stub
exactly once
Then this verification can be
added to the test to ensure
that indeed, an HTTP GET to
‘/hello-world’ has been made
exactly once
Some more verification examples
The same as the above, but less verbose
Verify that less than 5 HTTP POSTs were made to /requestLoan
Verify that 10 or more HTTP POSTs with a ‘Content-Type’ header value containing
‘application/json’ were made to /requestLoan
Now it’s your turn!
_exercises > WireMockExercises5Test.java
_Add WireMock verifications to the tests
_ Verify request properties as described in the comments
_Verify your solution by running the tests
_Answers are in answers > WireMockAnswers5Test.java
_Examples are in examples > WireMockExamplesTest.java
Section 6:
Extending WireMock
Extending WireMock
_In some cases, the default WireMock feature set
might not fit your needs
_WireMock is open to extensions
_Allows you to create even more powerful stubs
_Several options available
Section 6.1:
Filtering incoming
requests
Request filtering
_Modify incoming requests (or halt processing)
_This has a variety of use cases:
_Checking authentication details
_Request header injection
_URL rewriting
_Created by implementing the StubRequestFilterV2
interface
Request filtering – build
If the HTTP verb used equals DELETE…
Return an HTTP 403 and stop
processing the request
Else continue processing the request
Request filtering – use
An extension can be registered using:
- its class name (“com.example.HttpDeleteFilter”)
- the class (HttpDeleteFilter.class)
- an instance (new HttpDeleteFilter())
Now it’s your turn!
_exercises > extensions > BasicAuthFilter.java
_Implement a custom request filter that filters out all
requests that do not have the proper basic authentication
credentials
_Verify your solution by running the tests in exercises >
WireMockExercises6dot1Test.java
_Answers are in answers > extensions > BasicAuthFilter.java
_Examples are in examples > extensions >
HttpDeleteFilter.java
Section 6.2:
Building a custom
request matcher
Custom request matchers
_Add custom request matching logic to WireMock
_Can be combined with existing standard matchers
_Done by extending RequestMatcherExtension class
Custom request matcher – build
Get the value of the maxLength matcher parameter
Compare the request body length to the maxLength
parameter value and return the result as a MatchResult
Custom request matcher – use
Register the extension
Use custom matcher in a
stub definition using its
name (can be combined
with existing matchers) Specify desired parameter value
Now it’s your turn!
_exercises > extensions > RejectedHttpVerbsMatcher.java
_Implement a custom matcher that reads a list of rejected
HTTP verbs and matches the HTTP verb used in the incoming
request against it
_Verify your solution by running the tests in exercises >
WireMockExercises6dot2Test.java
_Answers are in answers > extensions >
RejectedHttpVerbsMatcher.java
_Examples are in examples > extensions >
BodyLengthMatcher.java
Section 6.3 is waiting on
https://github.com/wiremock
/wiremock/issues/2525
to be resolved
https://wiremock.org/docs
/extending-wiremock/
Appendix A:
JSON equivalents for
the Java examples
Our Hello world! mock
URL matching
Request header matching
Simulating a delay
Returning a fault response
Creating a
stateful mock
Use response templating
Use response templating
_When sent this JSON
request body:
_This stub returns a response with body “Pillars of
the Earth”:
Using WireMock extensions
Using a custom matcher
Registering a local
transformer
Specifying transformer
parameters
?
Ad

More Related Content

Similar to Wire Mock API, implementation using JAVA wiremock_workshop.pptx (20)

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
pleeps
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
Tricode (part of Dept)
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontend
Heiko Hardt
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
Ying Zhang
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
Mindfire Solutions
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
Eugene Dvorkin
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
James Phillips
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
Macon Pegram
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
Adam Stephensen
 
Data access
Data accessData access
Data access
Joshua Yoon
 
Flex Mock Testing Frameworks: Comparative Analysis
Flex Mock Testing Frameworks: Comparative AnalysisFlex Mock Testing Frameworks: Comparative Analysis
Flex Mock Testing Frameworks: Comparative Analysis
Nitin Khattar
 
Struts N E W
Struts N E WStruts N E W
Struts N E W
patinijava
 
Javascript-heavy Salesforce Applications
Javascript-heavy Salesforce ApplicationsJavascript-heavy Salesforce Applications
Javascript-heavy Salesforce Applications
Salesforce Developers
 
Struts Ppt 1
Struts Ppt 1Struts Ppt 1
Struts Ppt 1
JayaPrakash.m
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
Paul Churchward
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
Peter Arato
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
Hans Jones
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
chrisb206 chrisb206
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
pleeps
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
Tricode (part of Dept)
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontend
Heiko Hardt
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
Ying Zhang
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
Mindfire Solutions
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
Eugene Dvorkin
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
James Phillips
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
Adam Stephensen
 
Flex Mock Testing Frameworks: Comparative Analysis
Flex Mock Testing Frameworks: Comparative AnalysisFlex Mock Testing Frameworks: Comparative Analysis
Flex Mock Testing Frameworks: Comparative Analysis
Nitin Khattar
 
Javascript-heavy Salesforce Applications
Javascript-heavy Salesforce ApplicationsJavascript-heavy Salesforce Applications
Javascript-heavy Salesforce Applications
Salesforce Developers
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
Peter Arato
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
Hans Jones
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
chrisb206 chrisb206
 

Recently uploaded (20)

Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Ad

Wire Mock API, implementation using JAVA wiremock_workshop.pptx

  • 1. No API? No problem! API mocking with WireMock An open source workshop by … Originally created by Bas Dijkstra – [email protected] – https://www.ontestautomation.com
  • 2. What are we going to do? _Stubbing, mocking and service virtualization _WireMock _Exercises, examples, …
  • 3. Preparation _Install JDK (Java 17 or newer) _Install IntelliJ IDEA (or any other IDE) _Download or clone project _Import Maven project in IDE
  • 4. Section 0: An introduction to service virtualization
  • 5. Problems in test environments _Systems are constructed out of of many different components _Not all of these components are always available for testing _Parallel development _No control over test data _Fees required for using third party components _…
  • 6. Problems in test environments System under test Mainframe SaaS dependency Backend system Mobile app No suitable test data Limited access Under development Access fees
  • 7. Simulation during test execution _Simulate dependency behaviour _Regain full control over test environment _Available on demand _Full control over test data (edge cases!) _No third party component usage fees _…
  • 8. Problems in test environments System under test Mainframe SaaS dependency Backend system Mobile app No suitable test data Limited access Under development Access fees
  • 9. Simulation in test environments System under test Virtualized mainframe Virtualized SaaS dependency Virtualized backend system Virtualized mobile app Unrestricted access Unrestricted access Unrestricted access Unrestricted access
  • 12. Our system under test _ParaBank _The world’s least safe online bank _Request Loan process _Loan application is processed by 3rd party loan provider component
  • 15. What might we want to simulate? Start testing against features under development Delays, fault status codes, malformatted responses, … … Easy setup of state for edge cases
  • 16. Section 1: Getting started with WireMock
  • 17. WireMock _https://wiremock.org _Java _ports and adapters are available for many other languages _HTTP mock server _only supports HTTP(S) _Open source
  • 19. Starting WireMock (JUnit 4) _Via JUnit 4 @Rule _Without using JUnit 4 @Rule
  • 20. Starting WireMock (JUnit 5) _Uses the JUnit 5 Jupiter extension mechanism _Via @WireMockTest class annotation (basic configuration) _Programmatically using @RegisterExtension (full control)
  • 21. Starting WireMock (standalone) _Useful for exploratory testing purposes _Allows you to share WireMock instances between teams _Long-running instances _Download the .jar first java -jar wiremock-standalone-3.3.1.jar --port 9876
  • 22. Configure responses _In (Java) code _Using JSON mapping files
  • 23. An example mock defined in Java
  • 24. Some useful WireMock features _Verification _ Verify that certain requests are sent by application under test _Record and playback _ Generate mocks based on request-response pairs (traffic) _Fault simulation _… _Full documentation at https://wiremock.org/docs/
  • 25. Now it’s your turn! _exercises > WireMockExercises1Test.java _Create a couple of basic mocks _ Implement the responses as described in the comments _Verify your solution by running the tests in the same file _Answers are in answers > WireMockAnswers1Test.java _Examples are in examples > WireMockExamplesTest.java
  • 27. Request matching _Send a response only when certain properties in the request are matched _Options for request matching: _URL _HTTP method _Query parameters _Headers _Request body elements _…
  • 28. Example: URL matching _Other URL options: _urlPathEqualTo (matches only path, no query parameters) _urlMatching (using regular expressions) _urlPathMatching (using regular expressions)
  • 29. Example: header matching _absent(): check that header is not in request
  • 30. Example: using logical AND and OR _‘somevalue’ is matched _‘bananasomevaluebanana’ is matched _‘banana’ is not matched (does not contain ‘somevalue’) _‘123somevalue’ is not matched (contains numeric characters)
  • 31. Some more examples… Same behaviour as the previous example, using a slightly different syntax
  • 32. Matching on request body elements Matching only those request bodies that have a root level element fruits with a child element banana with value 2 {“fruits”: {“banana”: “2”, “apple”: “5”} }  MATCH {“fruits”: {“apple”: “5”} }  NO MATCH {“fruits”: {“banana”: “3”, “apple”: “5”} }  NO MATCH
  • 33. Matching using date/time properties Matching all dates after midnight of July 1, 2021 Matching all dates at least 1 month before the current date
  • 34. Other matching strategies _Authentication (Basic, OAuth(2)) _Query parameters _Multipart/form-data _You can write your own matching logic, too
  • 35. Fault simulation _Extend test coverage by simulating faults _Often hard to do in real systems _Easy to do using stubs or mocks _Used to test the exception handling of your application under test
  • 36. Example: HTTP status code _Some often used HTTP status codes: Consumer error Provider error 403 (Forbidden) 500 (Internal server error) 404 (Not found) 503 (Service unavailable)
  • 37. Example: timeout _Random delay can also be used _Uniform, lognormal distribution _Can be configured on a per-stub basis as well as globally
  • 38. Example: bad response _HTTP status code 200, but garbage in response body _Other options: _RANDOM_DATA_THEN_CLOSE (as above, without HTTP 200) _EMPTY_RESPONSE (does what it says on the tin) _CONNECTION_RESET_BY_PEER (close connection, no response)
  • 39. Now it’s your turn! _exercises > WireMockExercises2Test.java _Practice fault simulation and different request matching strategies _ Implement the responses as described in the comments _Verify your solution by running the tests in the same file _Answers are in answers > WireMockAnswers2Test.java _Examples are in examples > WireMockExamplesTest.java
  • 41. Statefulness _Sometimes, you want to simulate stateful behaviour _Shopping cart (empty / containing items) _Database (data present / not present) _Order in which requests arrive is significant
  • 42. Stateful mocks in WireMock _Supported through the concept of a Scenario _Essentially a finite state machine (FSM) _States and state transitions _Combination of current state and incoming request determines the response being sent _Before now, it was only the incoming request
  • 43. Stateful mocks: an example Responses are grouped by scenario name Response depends on both the incoming request as well as the current state The initial state should always be Scenario.STARTED Incoming requests can trigger state transitions State names other than Scenario.STARTED are yours to define
  • 44. Now it’s your turn! _exercises > WireMockExercises3Test.java _Create a stateful mock that exerts the described behaviour _ Implement the responses as described in the comments _Verify your solution by running the tests in the same file _Answers are in answers > WireMockAnswers3Test.java _Examples are in examples > WireMockExamplesTest.java
  • 46. Response templating _Often, you want to reuse elements from the request in the response _Request ID header _Unique body elements (client ID, etc.) _Cookie values _WireMock supports this through response templating
  • 47. Setup response templating (JUnit 4) _In code: through the JUnit @Rule _Global == false: response templating transformer has to be enabled for individual stubs
  • 48. Setup response templating (JUnit 5) _In code: through the JUnit @RegisterExtension _Argument == false: response templating has to be enabled for individual stubs
  • 49. Enable/apply response templating _This template reads the HTTP request method (GET/POST/PUT/…) using {{request.method}} and returns it as the response body This call to withTransformers() is only necessary when response templating isn’t activated globally
  • 50. One thing to keep in mind… … we need to explicitly assign our stub definition to that instance here, or else the stub definition will not be picked up! Because we’re explicitly initializing a WireMock instance here…
  • 51. Request attributes _Many different request attributes available for use _ request.method : HTTP method (example) _ request.pathSegments.[<n>] : nth path segment _ request.headers.<key> : header with name key _ … _All available attributes listed at https://wiremock.org/docs/response-templating/
  • 52. Request attributes (cont’d) _Extracting and reusing body elements _In case of a JSON request body: {{jsonPath request.body ‘$.path.to.element’}} _In case of an XML request body: {{xPath request.body ‘/path/to/element/text()’}}
  • 53. JSON extraction example _When sent this JSON request body: _This stub returns a response with body “Pillars of the Earth”: Again, this call to withTransformers() is only necessary when response templating isn’t activated globally
  • 54. Now it’s your turn! _exercises > WireMockExercises4Test.java _Create mocks that use response templating _ Implement the responses as described in the comments _Verify your solution by running the tests in the same file _Answers are in answers > WireMockAnswers4Test.java _Examples are in examples > WireMockExamplesTest.java
  • 56. Verifying incoming requests _Apart from returning responses, you might also want to verify that incoming requests have certain properties _Fail a test if these verifications aren’t met _You can do this with WireMock in a way very similar to mocking frameworks for unit tests (e.g., Mockito for Java)
  • 57. Verifying incoming requests Given this simple ‘hello world’ stub When we have this test that should invoke that stub exactly once Then this verification can be added to the test to ensure that indeed, an HTTP GET to ‘/hello-world’ has been made exactly once
  • 58. Some more verification examples The same as the above, but less verbose Verify that less than 5 HTTP POSTs were made to /requestLoan Verify that 10 or more HTTP POSTs with a ‘Content-Type’ header value containing ‘application/json’ were made to /requestLoan
  • 59. Now it’s your turn! _exercises > WireMockExercises5Test.java _Add WireMock verifications to the tests _ Verify request properties as described in the comments _Verify your solution by running the tests _Answers are in answers > WireMockAnswers5Test.java _Examples are in examples > WireMockExamplesTest.java
  • 61. Extending WireMock _In some cases, the default WireMock feature set might not fit your needs _WireMock is open to extensions _Allows you to create even more powerful stubs _Several options available
  • 63. Request filtering _Modify incoming requests (or halt processing) _This has a variety of use cases: _Checking authentication details _Request header injection _URL rewriting _Created by implementing the StubRequestFilterV2 interface
  • 64. Request filtering – build If the HTTP verb used equals DELETE… Return an HTTP 403 and stop processing the request Else continue processing the request
  • 65. Request filtering – use An extension can be registered using: - its class name (“com.example.HttpDeleteFilter”) - the class (HttpDeleteFilter.class) - an instance (new HttpDeleteFilter())
  • 66. Now it’s your turn! _exercises > extensions > BasicAuthFilter.java _Implement a custom request filter that filters out all requests that do not have the proper basic authentication credentials _Verify your solution by running the tests in exercises > WireMockExercises6dot1Test.java _Answers are in answers > extensions > BasicAuthFilter.java _Examples are in examples > extensions > HttpDeleteFilter.java
  • 67. Section 6.2: Building a custom request matcher
  • 68. Custom request matchers _Add custom request matching logic to WireMock _Can be combined with existing standard matchers _Done by extending RequestMatcherExtension class
  • 69. Custom request matcher – build Get the value of the maxLength matcher parameter Compare the request body length to the maxLength parameter value and return the result as a MatchResult
  • 70. Custom request matcher – use Register the extension Use custom matcher in a stub definition using its name (can be combined with existing matchers) Specify desired parameter value
  • 71. Now it’s your turn! _exercises > extensions > RejectedHttpVerbsMatcher.java _Implement a custom matcher that reads a list of rejected HTTP verbs and matches the HTTP verb used in the incoming request against it _Verify your solution by running the tests in exercises > WireMockExercises6dot2Test.java _Answers are in answers > extensions > RejectedHttpVerbsMatcher.java _Examples are in examples > extensions > BodyLengthMatcher.java
  • 72. Section 6.3 is waiting on https://github.com/wiremock /wiremock/issues/2525 to be resolved
  • 74. Appendix A: JSON equivalents for the Java examples
  • 79. Returning a fault response
  • 82. Use response templating _When sent this JSON request body: _This stub returns a response with body “Pillars of the Earth”:
  • 83. Using WireMock extensions Using a custom matcher Registering a local transformer Specifying transformer parameters
  • 84. ?