vic
vic

Reputation: 2818

Spring Data Rest Content Type

I am writing unit tests for my application with Spring Data Rest MongoDB. Based on Josh's "Building REST services with Spring" get start guide, I have the following test code:

    @Test
    public void readSingleAccount() throws Exception {
    mockMvc.perform(get("/accounts/"
            + this.account.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(contentType))
            .andExpect(jsonPath("$.id", is(this.account.getId())))
                    .andExpect(jsonPath("$.email", is(this.account.getEmail())))
                    .andExpect(jsonPath("$.password", is(this.account.getPassword())));
   }

And this test fails on the content type.

Content type expected:<application/json;charset=UTF-8> but was:    <application/hal+json>
Expected :application/json;charset=UTF-8
Actual   :application/hal+json

I don't see MediaType come with HAL. Is the content type defined in another class?

Upvotes: 4

Views: 3035

Answers (1)

thomi
thomi

Reputation: 1687

Had the same Problem when not using tomcat (which is configured to return utf-8 using Spring Boot). The solution is to set the accept header in your GET request so the response gets the correct content type:

private MediaType contentType = new MediaType("application", "hal+json", Charset.forName("UTF-8"));

and in your request, do

@Test
public void readSingleAccount() throws Exception {
mockMvc.perform(get("/accounts/"
        + this.account.getId()).**accept(contentType)**)
        .andExpect(status().isOk())
        .andExpect(content().contentType(contentType))
        .andExpect(jsonPath("$.id", is(this.account.getId())))
                .andExpect(jsonPath("$.email", is(this.account.getEmail())))
                .andExpect(jsonPath("$.password", is(this.account.getPassword())));
}

Upvotes: 6

Related Questions