Skip to content

Lab 4: Return String via HTTP GET


Create a "Controller" class that will return a plain String response to a GET request to an endpoint.

Clean Up

Before moving on, delete the following classes as we don't need them in their present form:

  • AnotherCoffeeOrderComponent
  • CoffeeOrderComponent
  • CoffeeOrderConfiguration
  • CoffeeOrderController
  • CoffeeOrderService
  • Startup

Compile the Code

Make sure the project compiles and tests pass before moving on.

a. Integration Test

Add the following new test class, CoffeeMenuWebTest in the same directory location as the existing CoffeeKioskApplicationTests class.

package com.welltestedlearning.coffeekiosk;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class CoffeeMenuWebTest {

    private MockMvc mockMvc;

    public void getFromCoffeeSizesEndpointReturns200Ok() throws Exception {

Create a new class in the production code directory called CoffeeMenuController like this:

package com.welltestedlearning.coffeekiosk;

import org.springframework.web.bind.annotation.RestController;

public class CoffeeMenuController {

Run this test, and you will see it fail with a 404 status code (Not Found).

b. GET Mapped Endpoint

To make the test pass, in the CoffeeMenuController, create a new method that takes no parameters and returns a String. Add the @GetMapping("/api/coffee/menu/sizes") annotation before the method. Inside the method, return the string small. It will look like this:

public String getCoffeeSizes() {
    return "small";

Now run the test, and it should pass.


Try it from the browser as well by running the application (run the CoffeeKioskApplication class) and pointing your browser to:


Spring MVC Annotation Reference

This reference of annotations might be helpful:

For more details, consult the Spring documentation here:


  • Endpoint: a URL that responds to HTTP requests
  • Mapping: the routing of an incoming request to a method based on a string defining the path
  • @RestController: Component annotation for class containing Mappings
  • @GetMapping: method annotation for mapping an incoming GET request to a method