How to Mock a Web Server in Your Java Applications

When you need to test an application that consumes a web API, you basically have two options:

  1. Use Testcontainers to start a container that will run the web API which your application will consume.
  2. Mock a Web Server to emulate the web API which your application will consume.

Many times, starting a container for that is not an option. For instance: you might not have a container environment available, or you just don’t have the artifacts to create that container (it might be a 3rd part API), or it is hard to emulate the needed behavior with containers.

Use Mocks in Testing? Choose the Lesser Evil!

Mocking Test Methodology 

The key idea of mocking is to replace real code (e.g. calls to a database or service) with artificial functionality that has the same return type. There are different approaches to this practice. Here, I explain best practices and why it might be better to avoid mocking to have real code quality.

User Service — Example to Be Tested With Mocks

Let's write a simple application that fetches users from HTTP service.