1

I already know how to write JUnit test cases (can also use Mockito). Thanks for the simple tutorials in the web for that. The only problem is that I can't find any examples on implementing it to an actual or let's say realistic project.

I have a simple REST web service which uses Servlets. It has an API method that sends a POST request to another web service then arranges the data as its response.

The API request is processed by two layers:

  • Servlet (Controller) - validates the request parameters
  • Service - The sender of the POST request to another web service

Here's what the service method does:

  1. Prepares a parameter data (some attributes are provided in the paramaters of this request, some are retrieved from the database)
  2. sends a request to another web service which responds with an image url for a QR Code
  3. Decodes the QRCode image and then responds to its request with the decoded text

What are the unit tests cases needed for this?

How about integration tests? Do I have to use ServletUnit, or can I just run the server and write tests with requests to the running server?

Chazz
  • 186
  • 1
  • 8

1 Answers1

0

Unit testing usually involves testing a single class in isolation. So you would need tests for the servlet class and for your service class as well.

If you're interested in unit testing a servlet, then have a look at these answers. In your case, you need to mock any external dependencies and check for example if valid parameters are sent to the service method.

Unit testing the service method includes mocking all external dependencies (web service, database) and only test the logic that's performed in the method (e.g. data is prepared correctly, QR decoding and responding with the correct text).

Most of the time you end up writing integration tests since you have multiple components which need to work together. There are multiple possible solutions to tackle that problem. You could create a separate integration testing environment which tries to replicate your production environment as closely as possible (web server, application server, database). For smaller projects that might be too much work and you could just spin up an embedded Tomcat with some kind of an in memory database (H2 for example). Keep in mind that for integration tests to be repeatable you might have to reinitialize the database for every test run.

In addition, you mentioned a web service which responds with a URL to a QR code. If you're not in control of that service, I would try to mock that service as well. You don't want to have a failing integration test because of a web service which might not be available 100% of the time.

Since your Servlet acts as a RESTful web service, take a look at rest-assured. This is a DSL for testing REST services.

Community
  • 1
  • 1
Indrek Ots
  • 3,701
  • 1
  • 19
  • 24