Java · Advanced level

Advanced level · Module 5: REST APIs with Spring Boot · Lesson 4 of 4

Testing Spring Boot APIs

Test services with plain unit tests and controllers with MockMvc, and run integration tests against a test database.

In this lesson you will

  • Write unit tests for services and slice tests for controllers with MockMvc
  • Write an integration test that runs the full application

Key concepts

unit test vs integration test@WebMvcTest and MockMvc@SpringBootTesttest data setup

The lesson

Test business rules with fast unit tests that create the service with fake repositories, without starting Spring. Most of your tests should be of this kind.

@WebMvcTest starts only the web layer, and MockMvc sends simulated requests: perform(post("/events").contentType(JSON).content(body)).andExpect(status().isCreated()). This checks mappings, validation and error handling.

@SpringBootTest starts the whole application, usually with a separate test database, to check that all layers work together. These tests are slower, so keep a few covering the main flows.

Step by step

  1. Write unit tests for EventService rules.
  2. Write MockMvc tests for 201, 400 and 404 responses.
  3. Write one @SpringBootTest for create-then-list.
  4. Run all tests with mvn test.

Practice activity

Write a complete test suite for the events API covering every endpoint and error case.

Expected result: All tests pass with mvn test, and removing a validation annotation makes at least one test fail.

Check your understanding

  1. Which annotation starts only the web layer for controller tests?

    Show answer

    @WebMvcTest.

  2. Why should most tests be unit tests?

    Show answer

    They are fast and pinpoint failures precisely; integration tests are slower and broader.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.