Lab 5: Return String via HTTP GET
Spring Annotation Reference
This reference of annotations might be helpful: http://engineering.pivotal.io/post/must-know-spring-boot-annotations-controllers/
Goal¶
Return a String response for a GET request to an endpoint.
Clean Up¶
Before moving on, delete the following classes as we don't need them anymore in their present form:
- CoffeeOrderComponent
- CoffeeOrderController
- CoffeeOrderRestController
- CoffeeOrderSecondComponent
- CoffeeOrderService
Make sure the tests still run 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.tedmyoung.coffeekiosk;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
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 getCoffeeSizesReturnsOk() throws Exception {
mockMvc.perform(get("/api/coffee/menu/sizes")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
Create a new class in the production code directory called CoffeeMenuController
like this:
package com.tedmyoung.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, create a new method that takes no parameters and returns a String
.
Add an @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 and pointing your browser to:
http://localhost:8080/api/coffee/menu/sizes
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