Skip to content

Lab 5: Return Domain Object via GET

Goal

Return a JSON string response for a GET request to an endpoint, but see why domain objects don't work well for this purpose.

a. CoffeeItem Class

Copy the CoffeeItem.java file into your src/main/java/com/welltestedlearning/coffeekiosk directory.

Check

Make sure everything still compiles and tests still pass.

b. Coffee Order Test

  1. Create a new REST controller named CoffeeOrderController.

  2. Create a new web test named CoffeeOrderWebTest similar to CoffeeMenuWebTest, but instead of testing against the CoffeeMenuController, you want to test against a new controller: CoffeeOrderController.

  3. Make sure the @WebMvcTest references the CoffeeOrderController.class as a parameter to the annotation, and add the following test:

    @Test
    public void getFromCoffeeOrderEndpointIs200Ok() throws Exception {
        mockMvc.perform(get("/api/coffee/order")
                          .accept(MediaType.APPLICATION_JSON))
               .andExpect(status().isOk());
    }
    
  4. Run it and it should fail with a 404 (Not Found), instead of the expected 200 (OK) status code.

c. Return Coffee Item

In the CoffeeOrderController, create a method that returns an instance of a CoffeeItem and is GET-mapped to /api/coffee/order.

e.g.: return new CoffeeItem("small", "latte", "milk");

If you did it correctly, the above test should now pass.

Browser

Run the application and go to http://localhost:8080/api/coffee/order

What do you see? Is it what you expected?


Glossary

Data Transfer Object
A Data Transfer Object, or DTO, which is an object that has only instance variables (data), with getters & setters that access to the data. DTOs are used by tools and libraries (such as Jackson) to extract named properties from an object based on naming patterns.
Domain Object
An object that implements domain (business) logic and has no direct references to infrastructure or frameworks. Uses "query" and "command" methods to interact with the object (instead of getters and setters).