Skip to content

Lab 4: Return String via HTTP GET

Goal

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;

@WebMvcTest(CoffeeMenuController.class)
public class CoffeeMenuWebTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void getFromCoffeeSizesEndpointReturns200Ok() throws Exception {
        mockMvc.perform(get("/api/coffee/menu/sizes"))
               .andExpect(status().isOk());
    }
}

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

package com.welltestedlearning.coffeekiosk;

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

@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:

@GetMapping("/api/coffee/menu/sizes")
public String getCoffeeSizes() {
    return "small";
}

Now run the test, and it should pass.

Browser

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

http://localhost:8080/api/coffee/menu/sizes


Spring MVC Annotation Reference

This reference of annotations might be helpful: http://engineering.pivotal.io/post/must-know-spring-boot-annotations-controllers/

For more details, consult the Spring documentation here: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping


Glossary

  • 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