Sometimes it turns out that the application we are trying to integrate doesn’t work just at the point when we need to run tests. As if it’s mocking us. However, this is not the main point of my article. Mocking also refers to something artificial, simulated, and this is the definition that interests us the most. Mocking, or simulating, in tests allows you to avoid downtimes of external services, but also helps to create test cases.
Fakes, stubs, mocks. What is mock testing?
In testing, you can take advantage of fakes, stubs, and mocks. In the article, I will focus on the latter.
In testing, mocking means simulating the response of a website so that it meets our expectations.
So, for example, mocking means pretending that a working system doesn’t work, or vice versa (e.g. in error handling testing). You can also simulate specific responses to check if the values returned are correctly calculated by your application.
What is unit testing?
Developers can test code by writing unit tests. Running unit tests allows you to check the elements of any application you create, be it a mobile application or a web application. Unit testing takes advantage of mocking on a wide scale.
Mocking in unit testing and e2e testing
In unit tests, there is more space to “show off”, so you can mock objects (class objects) that you interact with. In end-to-end tests, for the purposes of this article, we will take a closer look at mocked responses from websites. So why is it worth using mock testing?
Advantages of mock testing
Mocking has many advantages and uses. It allows you to:
Simulate
You can simulate different response values (e.g. testing timeout handling). Simulate constant response times to detect changes in your application by handling a given response unexpectedly.
Check
You can check how resistant your app is to downtime of external services caused by a bug in the new version, a failure, or by the fact that it is being installed. In the “ASAP” world, mocking helps to overcome such obstacles.
But bear in mind that when working only with mocks, you may overlook changes to the mocked components. Therefore, it is also worth checking the full end-to-end integration.
Mocking – examples
Theoretically, we only mock what is outside the scope of our activities. However, if some part of our system has also failed, it is worth temporarily fixing it to be able to test the next functionality. Imagine a scenario in which your system consists of two components:
- the server
- the client
The problem
Developers of the server component implement big changes, which cause instability in the testing environment. Developers of the client component are working on a business-critical change to be delivered within a given Sprint. Unfortunately, every client request to the server results in an error 503, and the achievement of the Sprint goal is at risk.
The solution
We know what responses to expect from the server (for example, we have recordings from the production environment or a previous working version of the server, or documentation). So with the mocking method, we can simulate the correct response from the server. The mocked response allows us to test our component and deliver the Sprint goal by implementing production code (only our component will be installed). Of course, it is also worth checking full integration (UAT / PREPROD) when possible. Running integration tests to check that our mocks are not outdated is a good practice. It may turn out that some changes that we have not been informed about are installed, and integration tests provide a chance to detect them.
Available mocking frameworks
There are plenty of applications that allow you to mock API Rest to choose from. I would like to describe a few of them and briefly point out the advantages and disadvantages of each.
SoapUI
A free version of the tool is more than enough to test the developed application in most cases. It has a graphical interface and you can easily click on the terminals you are interested in, which, unfortunately, is also a disadvantage of this solution (the need to click).
Postman
It shares the same set of advantages and disadvantages as SoapUI, but the GUI may be more user-friendly for some people. However, to create mocks, you need to create a free account.
MockServer and WireMock
They do not have GUI, but their configuration capabilities exceed the previously described solutions. They can be started as a standalone process or when building a project with automatic tests. Both are free and will meet the expectations of even the most demanding users. WireMock, however, has better scalability.
mocky.IO and beecepto.com
These are web solutions, and while they are easy to use, they have a significant disadvantage: they are located on a remote server, and response times and availability may be limited.
Mocking in practice
So let’s move on to practice. Based on the example of MockServer and Java, I will show you how to configure a sample mock without writing a single line of code, using Maven.
To configure Mock Server, all you need to do is:
- add dependencies in pom.xml:
<dependency> <groupId>org.mock-server</groupId> <artifactId>mockserver-netty</artifactId> <version>5.9.0</version> </dependency> <dependency> <groupId>org.mock-server</groupId> <artifactId>mockserver-client-java</artifactId> <version>5.9.0</version> </dependency>
- as well as the plugin that our server will run:
<plugin> <groupId>org.mock-server</groupId> <artifactId>mockserver-maven-plugin</artifactId> <version>5.9.0</version> <configuration> <serverPort>1080</serverPort> <logLevel>WARN</logLevel> </configuration> <executions> <execution> <id>process-test-classes</id> <phase>process-test-classes</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>verify</id> <phase>verify</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin>
From this we can see that our server will be started by Maven on localhost:1080 in the process-test-classes phase and stopped in the verification phase.
We build the project using the command:
mvn clean verify Dmockserver.initializationJsonPath = src / test / resources / REST / mockserver / initialize.json
And here a mysterious .json file appears that contains the entire configuration related to mocked endpoints – that is, determining the types and parameters of requests, as well as responses to these requests.
This is an example for the exchange rate from the NBP, accepting GET at the address
http://api.nbp.pl/api/exchangerates/tables/A/?format=json
and returning the response with the code 200 – OK, in JSON format, with the exchange rate for Thai baht:
[ { "httpRequest": { "method" : "GET", "path" : "/api/exchangerates/tables/A/", "queryStringParameters" : { "format" : [ "json" ] }, "httpResponse": { "statusCode" : 200, "headers" : { "Content-Type" : [ "application/json" ] }, "body": "[{ \"table\": \"A\", \"no\": \"022/A/NBP/2020\", \"effectiveDate\": \"2020-02-03\", \"rates\": [{ \"currency\": \"bat (Tajlandia)\", \"code\": \"THB\", \"mid\": 0.1111 }] }]" } } ]
Now we just need to replace the http://api.nbp.pl address with http: // localhost: 1080 and enjoy the lowest Thai baht rate in history visible in our tests.
As you can see, the configuration is not difficult, it doesn’t require you to write any code, and more mocks can be added by extending the JSON file.
Mocking in manual tests
If you want to use mocking in manual tests, I recommend the free version of the SoapUI tool. It has a graphical interface, which ensures that clicking the necessary configuration does not cause major issues.
Below is an example for our NBP:

After starting the application, we create a new project. Accordingly, we click File (1) and New SOAP Project (2)

Then give it a suitable name (1) and click OK.

Click on the newly created project PPM and choose New REST MockService (2)

Give it a suitable name (1) and confirm by clicking OK.

Here (1) we can see that our MockService is running on the default port 8080.

Add an action to the website corresponding to the HTTP request. Click PPM on the website (1) and choose to Add new mock action (2).

At this point (1) we choose the method GET / POST / PUT and many others. We are interested in GET.
We also provide the path to the API (2) and confirm by clicking OK.

Since we have a defined request, it is high time to add a response. Click PPM on the request (1) and select New MockResponse (2).

The answer needs a name, too. Enter it (1) and confirm by clicking OK.

In the answer, add the heading (1) and type Content-Type (2). This is not necessary, but it’s best to add any headers that appear in the actual server response.

Here is the answer in JSON format, so we complete the application/json (1). In the form below (2), paste the expected response body (this is the JSON object that normally returns the server and to which the mock will respond).

We only have to start the server. Double-click our MockService (1) and Start (2).
Our server is already running and if we make a query at http: //localhost: 8080 / api / exchange rates / tables / A /, in log (3) we will see information about the success of this operation.
As you can see, SoapUI requires a little more clicking, but it is far more friendly for people who are taking their first steps in this field. Additionally, we get a standalone server.
Mock testing – summary
Mocking in tests is, of course, a much wider topic. I hope that in this short article I was able to encourage you to check out the possibilities that mocking offers. There are plenty of free and intuitive applications that can help you take your first steps into the world of mocking.