Skip to main content

Updated for Fall 2026

Now that we’ve covered how to test the persistence and service layers, the next step in our testing process is covering the REST API endpoints, which are found in the controllers package. Most modern applications, particularly web applications, communicate with the outside world with a REST API, which works by exposing a set of endpoints that you can send HTTP requests to in order to carry out certain actions. Spring, the framework we use for building our web application, provides functionality for creating and testing REST API endpoints.

An API (or Application Programming Interface) defines a specification for how to communicate with a computer program or library. An API lays out what functionality is offered, what parameters must be provided when making calls, and provides some guarantees about the return type given the preconditions are satisfied. Fundamentally, a complete and well-documented API makes it easier to use a piece of code as a “building block” for building a larger system.

A REST API is a sub-type of API typically provided by Internet-facing systems. The goal of REST APIs is to provide painless communication and interoperability between these Internet-facing applications and systems. REST APIs typically allow (often with some sort of authentication) a manipulation of the various types of entities or objects that a web application may want to work with. For CoffeeMaker, our web application will work with recipes and inventory.

The key concept behind REST APIs is that they are inherently stateless, that is, everything that a server needs to know to complete a request or a client needs to know about the results is contained within the request itself. This is contrary to the notion of a server maintaining a session where it stores information about a series of transactions with a particular client, or cookies where a client keeps similar information stored on its end.

Typically, REST API operations are carried out over HTTP; consequently most REST API actions are based around HTTP verbs (GET, POST, PUT, DELETE). The actions typically available are:

HTTP Verb Action Example Result
GET Retrieve record(s) GET /users/ Retrieves all users
DELETE Delete record(s) DELETE /users/1 Deletes user with id 1
POST Create record POST /users/ Creates a new user
PUT Update record PUT /users/6 Updates user 6

One of the advantages of REST APIs is that they are straight forward to test. Essentially, they let you treat the underlying application as a closed box – you don’t care about how the insides work, merely that there is an API endpoint that says “If you send me a request with data that matches , I will take some action and send you back data matching ".

For this step of the workshop, we’ll see that in action: we’ll see how you can call upon the API endpoints to make certain actions get taken. We’ll create API tests for RecipeController.

Two Reference Tests

You have been given two complete tests for InventoryController, and they take deliberately different approaches. Read both before you start writing.

  InventoryControllerTest InventoryControllerWebMvcTest
Annotation @SpringBootTest + @AutoConfigureMockMvc @WebMvcTest(InventoryController.class)
What starts The whole application Only Spring’s web layer
The service The real one A Mockito mock (@MockitoBean)
Database Real MySQL None
Speed Seconds Roughly ten times faster
Proves Controller, service, repository, and database work together The controller itself behaves correctly

Neither replaces the other. The integration test catches wiring mistakes that a mock will happily hide. The web-layer test does three things the integration test cannot, which we come back to in Testing a Controller in Isolation.

This workshop walks through the integration style first, because it is closer to what you have already done.

Getting Started

We want to follow our process expectations, so do the following:

  • Create an issue for the task of completing the API Testing Workshop.
  • Create a branch off development for working on the API Testing Workshop.
  • Switch to the branch.

We will focus on testing the Recipe requirements through the endpoints RecipeController provides. Review the requirements to better understand the tests.

Creating JSON

You’ve been provided a class, edu.ncsu.csc326.coffee_maker.TestUtils, that serializes Java objects to JSON so you can send them across the API. It already exists — you do not need to create it.

So, what is JSON? JSON is JavaScript Object Notation, which provides a textual representation of objects that can be transferred between parts of a system. Serialization is the creation of a text-based representation of an object’s state. We’ll serialize our Java objects into JSON for working with our REST API.

We could construct our JSON by hand, but that’s really annoying and prone to needless mistakes. TestUtils.asJsonString() does it for us:

public static String asJsonString ( final Object obj ) {
    try {
        return MAPPER.writeValueAsString( obj );
    }
    catch ( final JsonProcessingException e ) {
        throw new IllegalArgumentException( "Could not serialize " + obj, e );
    }
}

MAPPER is a Jackson ObjectMapper. Jackson is the serializer Spring Boot itself uses for the REST API, so the JSON your test builds is produced the same way as the JSON the application actually sends — which means a test cannot pass because your test serializer and the application’s disagree.

Setting Up API Testing

Next, we’ll need a new class to put our tests in. Under src/test/java, in the edu.ncsu.csc326.coffee_maker.controllers package, create a class RecipeControllerTest.

To make the API tests run without launching a server first, Spring needs three annotations on the class:

@SpringBootTest
@AutoConfigureMockMvc
@Transactional
public class RecipeControllerTest {
  • @SpringBootTest starts the application context.
  • @AutoConfigureMockMvc gives you a MockMvc that sends requests straight into the controller, with no server and no network.
  • @Transactional on the class wraps every test in a transaction that is rolled back afterwards. You do not need it on individual methods.

We use several static imports to cut down on verbosity:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

Inside the class, autowire MockMvc and an EntityManager, and clear the recipes table before each test. InventoryControllerTest uses a JPQL bulk delete through the EntityManager, which keeps the test from reaching down into the repository — a controller test that injects a repository is testing three layers at once.

/** Mock MVC for testing controller */
@Autowired
private MockMvc mvc;

/** Reference to EntityManager */
@Autowired
private EntityManager entityManager;

/**
 * Sets up the test case.
 * @throws java.lang.Exception if error
 */
@BeforeEach
public void setUp() throws Exception {
	entityManager.createQuery("DELETE FROM Recipe").executeUpdate();
}

Now create a test method for getting all recipes in the system. Add the @Test annotation to indicate this is a JUnit test.

@Test
public void testGetRecipes() throws Exception {

}

Working with Endpoints

Writing tests for controller methods looks very different from the JUnit tests you’re used to. A nice quick reference for testing the different types of endpoints is available.

If you open RecipeController, you’ll see a method getRecipes() available at GET /api/recipes that returns all of the recipes in the system. While the declared return type is List<RecipeDto>, Spring automatically serializes that to a JSON array. Our test calls the endpoint and checks what comes back (you will need to handle exceptions — put your cursor on the error and press Alt+Enter to let IntelliJ generate the handling for you):

String recipe = mvc.perform(get("/api/recipes"))
					.andDo(print())
					.andExpect(status().isOk())
					.andReturn().getResponse().getContentAsString();

As you probably expect, this says “call this API endpoint and get all the recipes, print the results, expect the call to go through successfully, and then also grab the results for me as a string”. While in the long run you’d remove the printing, it is useful for debugging. Since there are no recipes, the body is [].

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /api/recipes
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = edu.ncsu.csc326.coffee_maker.controllers.RecipeController
           Method = edu.ncsu.csc326.coffee_maker.controllers.RecipeController#getRecipes()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json"]
     Content type = application/json
             Body = []
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Testing the Response

So far we’ve seen how to make a request and get a response back. We can check the contents of the response body as a string using contains. Since we don’t allow recipes with duplicate names, this is useful for checking whether a recipe exists before we try to create it:

if (!recipe.contains("Mocha")) {
  //create a new Mocha recipe

}

For this test, we want to check that the recipes table is empty.

@Test
public void testGetRecipes() throws Exception {
	String recipe = mvc.perform(get("/api/recipes"))
			.andDo(print())
			.andExpect(status().isOk())
			.andReturn().getResponse().getContentAsString();
	assertFalse(recipe.contains("Mocha"));
}

For structured checks, jsonPath() is usually better than string matching — it reads a specific field out of the JSON rather than searching the whole body. InventoryControllerTest uses it throughout:

.andExpect(jsonPath("$.coffee").value(5))

Testing Create Recipe

Create a method testCreateRecipe().

The point of an API endpoint is that you get to treat whatever is behind it as a closed box. That fantasy means we pretend we don’t know how to save objects to the database with .save(). So how do we create one? Make another API request.

We slightly break the fantasy by building a Java RecipeDto, but rather than saving it, we send it to the endpoint. *Dto objects represent the data shared across API endpoints, and TestUtils turns them into JSON.

Use the RecipeDto constructor that does not take an id — ids are assigned by the database.

@Test
public void testCreateRecipe() throws Exception {
	RecipeDto recipeDto = new RecipeDto("Mocha", 200, 2, 1, 1, 3);

	mvc.perform(post("/api/recipes")
			.contentType(MediaType.APPLICATION_JSON)
			.content(TestUtils.asJsonString(recipeDto))
			.accept(MediaType.APPLICATION_JSON))
			.andExpect(status().isOk())
			.andExpect(jsonPath("$.name").value("Mocha"))
			.andExpect(jsonPath("$.price").value(200))
			.andExpect(jsonPath("$.coffee").value(2))
			.andExpect(jsonPath("$.milk").value(1))
			.andExpect(jsonPath("$.sugar").value(1))
			.andExpect(jsonPath("$.chocolate").value(3));
}

What are we doing here? We make a POST request (POST is the HTTP verb used to create objects; more are available here) to /api/recipes, passing data describing the recipe to create. contentType specifies that we’re sending JSON, and content is the actual data. TestUtils.asJsonString turns the Java object into JSON looking something like:

{"id":null,"name":"Mocha","price":200,"coffee":2,"milk":1,"sugar":1,"chocolate":3}

Then we check that the correct values come back by reading fields out of the response JSON by name.

Get Recipes after Create

Next, call the endpoint to retrieve recipes again and make sure the recipe you just created is actually there. Use the first API call above and check that the correct values are in the list.

Testing a Controller in Isolation

RecipeController.createRecipe() does not always return 200 OK. Read it: it returns 409 CONFLICT when a recipe with that name already exists, and 507 INSUFFICIENT_STORAGE when the system already holds the maximum number of recipes.

The conflict case is easy to arrange with a real database — create the recipe twice. The storage case is not: you would have to create the maximum number of recipes first, just to test one line of the controller. That is what the second reference test is for.

InventoryControllerWebMvcTest uses @WebMvcTest, which starts only the web layer and gives the controller a mock service instead of the real one:

@WebMvcTest(InventoryController.class)
public class InventoryControllerWebMvcTest {

	@Autowired
	private MockMvc mvc;

	/** Stands in for the real InventoryService. */
	@MockitoBean
	private InventoryService inventoryService;

Note @MockitoBean, not @MockBean. They do the same job, but @MockBean was deprecated in Spring Boot 3.4, so it is what older tutorials will show you.

Because you control what the service does, you can do three things the integration test cannot.

1. Decide what the service returns, so the controller can be checked against values that would be awkward to arrange in a real database:

when(inventoryService.getInventory()).thenReturn(new InventoryDto(1L, 5, 10, 15, 20));

2. Inspect what the controller passed down. This is the only way to prove the JSON request body was bound to a DTO correctly — the response alone cannot tell you, because the mock decides what comes back regardless of what it was given:

ArgumentCaptor<InventoryDto> sentToService = ArgumentCaptor.forClass(InventoryDto.class);
verify(inventoryService).updateInventory(sentToService.capture());

InventoryDto captured = sentToService.getValue();
assertAll("InventoryDto the controller built from the request body",
		() -> assertEquals(5, captured.getCoffee()),
		...);

3. Make the service fail on command, so error handling can be tested at all:

when(inventoryService.updateInventory(any(InventoryDto.class)))
		.thenThrow(new ResourceNotFoundException("Inventory does not exist."));

mvc.perform(put("/api/inventory") ... )
		.andExpect(status().isNotFound());

That returns 404 rather than 500 because ResourceNotFoundException carries @ResponseStatus(HttpStatus.NOT_FOUND).

One more habit worth copying from the reference: after stubbing a call, verify() that the controller actually made it. A stub sits there quietly whether or not anyone calls it, so a test can pass against a controller that never talked to the service at all.

Your Tasks

Finish testing RecipeController. It exposes four endpoints:

Endpoint Method What your test should establish
GET /api/recipes getRecipes() Worked example above — extend it to show created recipes come back
GET /api/recipes/{name} getRecipe() A recipe that exists is returned; consider what should happen for one that does not
POST /api/recipes createRecipe() The 200 case above, plus the 409 CONFLICT duplicate-name case
DELETE /api/recipes/{id} deleteRecipe() The recipe is gone afterwards — check with a follow-up GET

For the 507 INSUFFICIENT_STORAGE case, write a RecipeControllerWebMvcTest using the isolation style above. Mocking RecipeService lets you produce that condition in one line instead of creating recipes until the system fills up.

Run Tests

Run your tests and make sure they all pass. Then run them again with coverage — right click src/test/java and select Run ‘All Tests’ with Coverage.

Milestone 1 asks for 60% statement coverage and 50% branch coverage across the Inventory* and Recipe* classes. Having tested all three layers, you should be at or near that now. The build reports your coverage but does not fail on a shortfall, so check the number rather than trusting a green check — see Coverage.

Integrate

Your new tests should be passing. It’s time to do the following:

  • Commit the changes on your API testing workshop branch.
  • Create a pull request to merge the API testing workshop branch to the development branch.
  • Approve the merge request and ensure that the tests are building on GitHub via GitHub Actions.

Merge to Main

Now that you’re done testing the recipe functionality, you can merge your development branch into main. Check that everything is building.

Next Steps

Head back to the testing workshop.