0% found this document useful (0 votes)
8 views

API mocking

Uploaded by

rabia shermeen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

API mocking

Uploaded by

rabia shermeen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Best Practices for API Mocking

Intro to API Mocking | 1


Contents
3 | Intro to API Mocking
What is a mock?

Mocks, stubs, virtual services – which one do I use?

How are these used in tests?

Mocking vs. contract testing

When would I use contract testing?

When to mock

7 | API-first development & API mocking


API as a contract

How do mocks and contract testing accelerate API “design first”?

Let’s explore these

Why should I care about mock “drift”?

Instances that help speed

A simple case study

9 | Real-life mocking scenarios


Build out a test project – virtually

Why SmartBear for mocking?

Intro to API Mocking | 2


Intro to What is a mock?

High quality. Fast. Cheap. Safe. In the ideal scenario,


API Mocking
by short cycles and iterative sprints), maintaining
development, testing, and operations teams work these ideals become increasingly difficult. Mocking
harmoniously to deliver high-quality applications, provides opportunities for both developers and
on schedule, under budget, and error free. testers to build sandbox environments and “mock,”
or simulate, how services behave – this ensures
But as applications become more complex, and
high quality throughout the entire software
companies adopt Agile methods (characterized development lifecycle.

Intro to API Mocking | 3


Mocks, stubs, virtual services – 3. A virtual service: A stand-in for a service and is We often see examples where a service or
created through virtualizing a service definition, dependency is external and not suitable to run
which one do I use?
e.g. OAS definition, or created by recording tests against (no sandbox environment or making
Mocking is one of those terms that cover a lot of traffic from an internal or external endpoint. requests results in costs not budgeted for).
ground, so let’s be clear on what we mean.
For the latter, consider it a mock on steroids. It This is where mocking comes in: Instead of developing
The most common term for creating simulated is a virtual service that works similarly to the real code with actual external dependencies in place, a

components is mocking, but others are also used, API you create. It imitates the real API, defines mock of those dependencies is created and used.

and partly apply to different things: stubbing, operations that clients of your real API will call, You can make the mock “intelligent” enough to return
receives client requests, and simulates responses. similar results to the actual component it simulates,
mocking, and virtualization (or virtual services).
It establishes a common ground for teams to thus letting development move forward without being
1. A stub: A minimal version of a service or communicate and facilitate artifact sharing. hindered by unavailability of services or systems.
API, usually configured to return predictable
or even hardcoded data. The response is These services are often shared with other As the software development lifecycle progresses,
often coupled to the test case or suite, and development teams and frequently support more the need for more intelligent and dynamic
the tests are going to depend on that data. than one protocol (HTTP, MQ, TCP, etc.). They can responses requires a more intelligent mock. This is
It is used often when the suite of tests is be called remotely (over HTTP, TCP, etc.), whereas why we often see virtual services used for system
simple. Stubs are often handwritten; some stubs and mocks most often work in-process testing where stubs and mocks for unit/module/
can be generated by tools for you. acceptance testing.
directly with classes, methods, and functions.

2. A mock: Usually verifies outputs against some Virtual services are often deployed in an environment
expectations, which can be set in the test. It How are these used in tests? where they can be shared and used by many
is most useful when you have a large suite of teams simultaneously, whereas stubs would be
Developers are usually required to test that
tests and each of the tests needs different individual instances per team.
the service or application they are working on
responses or data, or you want to test different
integrates with other system components via APIs.
scenarios. Maintaining a stub in that case could
be manual and costly, so you can use a mock Frequently, they are unable access those systems

instead. Mocks often focus on interactions and during development due to security, performance,
are usually stateful; for example, you can verify ownership, or maintenance issues that make them
how many times a given method was called. unavailable – or they simply might not exist yet.

Intro to API Mocking | 4


Mocking vs. contract testing When would I use contract testing?

Contract testing is a technique used for testing Contract testing is immediately applicable
an integration point by checking each application anywhere where you have two services that need
in isolation. It ensures the messages it sends or to communicate – such as an API client and a web
receives conform to a shared understanding that frontend.
is documented in a “contract.”
Contract testing really shines in an environment
For applications that communicate via HTTP, with many services (as is common for a microservice
these “messages” would be the HTTP request and architecture) are being developed in parallel and
response, and for an application that used queues, need to be tested at speed. Having well-formed
this would be the message that goes in the queue. contract tests makes it easy for developers to avoid
version hell. Contract testing is the killer app for
In practice, a common way to implement contract
microservice development and deployment.
tests (the way Pact does it) is simple. Check that all
the calls to your test-double returns with the same
results that would come from the real application.

But wait ...this sounds like mocking. True, they are


both ways of simulating requests and responses,
and testing how components of your services
interact. But there are differences.

Let’s consider how mocking and contract testing


can be used at different points of your software
development lifecycle.

Intro to API Mocking | 5


When to mock

There’s an array of use cases for mocking. At a


high level, mocking should be used to help conduct
different types of testing, thus increasing quality
and speed. Here at SmartBear, we recommend
mocking when your service is not developed yet or
where you use internal or external dependencies
like system calls or accessing a database that is not
readily available.

For the next chapter, we’ll talk about how


mocking and contract testing work as part of your
development workflows, plus examine some use
cases based on our experiences with customers.

Test Environment

API Mocking 101


Other
dependent Mocked
internal responses
services

Mocked service API call


A sandbox to learn how your APIs behave
Internal
Your
dependent
infrastructure
service Watch the Webinar

Intro to API Mocking | 6


API-first How do mocks and contract testing generate things that improve the developer

accelerate API “design first”? experience, like interactive documentation, mocks

development & Contracts are fine as written definitions or


to try it out, client libraries, and SDKs.

documents, but an API is a business asset. And you Why should I care about
API mocking and your teams (and partners) are going to want to
mock “drift”?
demonstrate it and try it out.
In the Agile world of software development, the
Mocks and contract testing are important in validating
the premise of the contract and ensuring that the pace and rate of change of services are fast, and

requirements are implemented. it’s a challenge to keep your mocks up to date,


especially in a complex microservice architecture.
Both API-first and API design-first emphasize
the importance of documents and contracts. Where API definitions and mocks are not integrated
They provide a reliable source of truth for API
and when your mocks and your live services
design and development teams. Both approaches
are deviating from one another due to rapid
have stakeholders getting involved early in the
design process before writing any code, providing development updates, we call this mock drift. This

several advantages. is a great use case where contract testing helps


you keep pace with the changes in your service and
Let’s explore these
reduces your need to keep mocks updated at a
Teams can work in parallel, using the API definition to microservice layer.
create and mock APIs, which allows producers and
consumers to try out API designs and test APIs before You may then focus your efforts to update mocks
deploying them. You don’t have to wait on other teams as part of less frequent integration tests. This way,
to complete different phases of the API. you leverage contract testing and mocks as part

You can use API definitions and mocks, especially of your development flows and teams are able to

when hosted in tools like SwaggerHub, to automatically accelerate with the right kind of test at the right time.

Intro to API Mocking | 7


The mock is updated every time you save your API. | Making your APIs available to others. Before
The mock helps you test your API when designing it, they commit to using them, that is. With mocking,
that is, before it is implemented by developers. Also, you can provide a simulation of the actual API for
the mock allows developers to start building client
testing purposes without the need to give access
applications even before the API backend is ready.
to your product or provision credentials. Demos
Instances that help speed can benefit from API mocking in the same way.

Some examples of where mocking accelerates


development and improves collaboration: A simple case study

| The design phase of an API. You can quickly A development company has been developing
collaborate with stakeholders and apply changes microservices. They used OAS-based APIs to
to refine the API contract without waiting for a communicate between them. Teams used to have
server deployment or the development team’s to wait for one another to finish the APIs before
availability. With mocking, you can try out the
starting work. This dependency slowed down
changes and ensure they work as expected.
projects and caused stress.
| Collaboration and reduced dependencies.
This is helpful between development teams, Using API mocks, they could simulate their API API Mocking 102
especially your frontend and backend. It’s perfect schemas and defined behaviors. They developed both
when API is still under development, and you sides of their service in parallel, without having to wait How to create mocks
want to avoid bottlenecks for multiple teams. on code to be written before testing can happen.
and prevent drift

Watch the Webinar

Intro to API Mocking | 8


Real-life mocking Developers are typically tasked with writing code
that integrates with other system components
You may need to test against your API gateway as part
of application testing – but the gateway APIs do not

scenarios
via APIs. Unfortunately, it might not always be have a sandbox. We frequently see customers citing
desirable or even possible to access those systems systems owned by production that are not made
during development.
available to testing and cannot be modified to reflect

There could be security, performance, or maintenance different test cases.


issues that make them unavailable. We frequently
This dependency (and lack of availability) causes
see teams dependent on services owned by other
delays for test teams and leads to frustration.
groups, but they are not accessible for testing or
Requests to internal and external services during
modifying. They’re either in production, or say,
an external service needs to be called, but it’s not test runs also can cause other issues:

available or suitable for testing.


| Tests failing due to connectivity.
This is where mocking via recording comes in: When
| Test suites running slow due to networking
functional testing a component that depends on
and access.
external APIs, mocking can be very useful.

For example, you might need to test a geo-location | Hitting third-party API rate limits.

functionality in your component that in turn uses


| No sandbox or staging server for test cases.
Google Maps APIs to coordinate lookups. Instead
of using the actual Google Maps API, you could use Mocking via recording means recording HTTP or
a corresponding mock that returns known results HTTPS traffic to some existing API and creating a
to your component. virtual service from the recorded requests and

This helps you validate the results from your responses it detected. Another approach is to record

component, as they are not affected by eventual a live interaction and replay it back during tests. This
inconsistencies in the external components. So an mock can then be configured to support the test use
added benefit to mocking is that you keep your cases and run as often and wherever required to
usage quota of external APIs to a minimum. support testing.

Intro to API Mocking | 9


Build out a test project – virtually | Customer evaluation – Providing evaluation and
pre-sales opportunities.
With SmartBear solutions, you can configure How does it work?
the route options property and set the | Avoiding API dependencies – Developing against

functioning mode of a virtual service. You future or unavailable functionality.

can configure your service to forward all As you work through the software development
incoming requests to a real API and create process, you can use mocks at different stages to
virtual operations for those requests. test different scenarios and update your mocks to
reflect what you expect real-world conditions to be.
Once you have the recording created and
configured, you can start to build out the other These capabilities provide real value to your teams
parts. The recorded mock can be left to run as and enable development and testing to progress in
often and as long as you need, and your team parallel. They also provide the following benefits:
can utilize it as part of unit or integrations tests.
| Sandbox environments to modify as you need
If you want to validate your mock has not
| Multiple versions to support different test use
drifted, incorporate contract testing against
cases and outcomes
it and monitor changes to the service from
what your producer or consumer expects. | Lower cost of running tests against rated
external services
Then use your API mock in different scenarios.

| External dependencies – Testing unexpected


| One environment to establish a source of truth API Mocking 103
behavior and third-party dependencies. | Monitor traffic to the mock and analyze behav-
iors to validate expectations See how your APIs work
| Isolated development – Development environ-
ment for use by operation and architects.
While these are more basic examples, we hope across systems
this book provides insights into using mocks
| Early functional testing – Starting testing work in development. If there are any topics you
early in development, even before actual com- want to discuss further with us, please contact Watch the Webinar
ponents are available. us and speak with our Solution Engineers.

Intro to API Mocking | 10


Try it yourself.
Go from mock academic to mock practitioner. Learn more about
our approach to the API lifecycle, or download a free trial to start
seeing your mock APIs in real life.

The Single Source of Truth The All-in-One Automated The Most Comprehensive
for API Development API Testing Platform Contract Testing Platform

Create Free Account Start Free Trial Try for Free


Intro to API Mocking | 12

You might also like