Skip to content

Lab 8: Return XML Media Type

Goal

  • Learn how to implement content-negotiation.

a. Add Failing Test

Add the following test to the CoffeeOrderWebTest:

@Test
public void getCoffeeOrderAsXmlIsOk() throws Exception {
  MvcResult mvcResult = mockMvc.perform(get("/api/coffee/order")
                                            .accept(MediaType.APPLICATION_XML))
                               .andExpect(status().isOk())
                               .andReturn();

  String xmlContent = mvcResult.getResponse().getContentAsString();
  assertThat(xmlContent)
      .contains("<CoffeeItemResponse>",
                "<id>1</id>",
                "<kind>latte</kind>",
                "<creamer>milk</creamer>",
                "<size>small</size>",
                "<price>$1</price>",
                "</CoffeeItemResponse>");
}

When you run it, it should fail. Note how it fails: what is the return status code?

b. Implement XML Support

Add the following dependency to your pom.xml file in the <dependencies> section:

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Now run the test. What happens?

c. Produces Annotation

To force a mapped method to return a specific set of media types, you can use the produces parameter. Change the @GetMapping in the CoffeeOrderController to be:

@GetMapping(value = "/api/coffee/order", produces = MediaType.APPLICATION_JSON_VALUE)

Run the test again. What happens?


NOTE Before continuing, make sure to restore the mapping to the way it was, i.e.:

@GetMapping("/api/coffee/order")