我正在使用Spring Data Rest MongoDB为我的应用程序编写单元测试。基于Josh的“使用Spring构建REST服务”获取入门指南,我有以下测试代码:
@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())));
}
此测试在内容类型上失败。
Content type expected:<application/json;charset=UTF-8> but was: <application/hal+json>
Expected :application/json;charset=UTF-8
Actual :application/hal+json
我没有看到MediaType来自HAL。内容类型是否在另一个类中定义?
答案 0 :(得分:5)
当不使用tomcat(配置为使用Spring Boot返回utf-8)时有同样的问题。解决方案是在GET请求中设置accept标头,以便响应获得正确的内容类型:
private MediaType contentType = new MediaType("application", "hal+json", Charset.forName("UTF-8"));
并在您的请求中,执行
@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())));
}