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¶
-
Create a new REST controller named
CoffeeOrderController
. -
Create a new web test named
CoffeeOrderWebTest
similar toCoffeeMenuWebTest
, but instead of testing against theCoffeeMenuController
, you want to test against a new controller:CoffeeOrderController
. -
Make sure the
@WebMvcTest
references theCoffeeOrderController.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()); }
-
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).