Skip to content

Lab 6: 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/tedmyoung/coffeekiosk directory. Make sure everything still compiles.

b. Coffee Order Test

Create a new REST controller named CoffeeOrderController.

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. Make sure the @WebMvcTest references the CoffeeOrderController.class. Add the follow test to it:

@Test
public void getCoffeeOrderIsOk() throws Exception {
  mockMvc.perform(get("/api/coffee/order")
                      .accept(MediaType.APPLICATION_JSON))
         .andExpect(status().isOk());
}

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 happened? 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) and getters & setters for access to the data.
Domain Object
An object that implements domain (business) logic and has no direct references to infrastructure or framework. Uses "query" and "command" methods to interact with the object (instead of getters and setters).