我正在使用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())));
}
Run Code Online (Sandbox Code Playgroud)
此测试在内容类型上失败.
Content type expected:<application/json;charset=UTF-8> but was: <application/hal+json>
Expected :application/json;charset=UTF-8
Actual :application/hal+json
Run Code Online (Sandbox Code Playgroud)
我没有看到MediaType带有HAL.内容类型是否在另一个类中定义?
不使用tomcat时遇到同样的问题(配置为使用Spring Boot返回utf-8).解决方案是在GET请求中设置accept标头,以便响应获取正确的内容类型:
private MediaType contentType = new MediaType("application", "hal+json", Charset.forName("UTF-8"));
Run Code Online (Sandbox Code Playgroud)
在你的请求中,做
@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())));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2025 次 |
| 最近记录: |