我正在尝试对我的 Controller 进行一些单元测试。无论我做什么,所有 Controller 测试都会返回
java.lang.AssertionError: Content type not set
我正在测试这些方法是否返回 json 和 xml 数据。
这里是 Controller 的例子:
@Controller
@RequestMapping("/mypath")
public class MyController {
@Autowired
MyService myService;
@RequestMapping(value="/schema", method = RequestMethod.GET)
public ResponseEntity<MyObject> getSchema(HttpServletRequest request) {
return new ResponseEntity<MyObject>(new MyObject(), HttpStatus.OK);
}
}
单元测试是这样设置的:
public class ControllerTest() {
private static final String path = "/mypath/schema";
private static final String jsonPath = "$.myObject.val";
private static final String defaultVal = "HELLO";
MockMvc mockMvc;
@InjectMocks
MyController controller;
@Mock
MyService myService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter(),
new Jaxb2RootElementHttpMessageConverter()).build();
when(myService.getInfo(any(String.class))).thenReturn(information);
when(myService.getInfo(any(String.class), any(Date.class))).thenReturn(informationOld);
}
@Test
public void pathReturnsJsonData() throws Exception {
mockMvc.perform(get(path).contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath(jsonPath).value(defaultVal));
}
我正在使用: Spring 4.0.2 联合 4.11 Gradle 1.12
我看到了SO问题Similiar Question但无论在我的单元测试中 contentType 和 expect 的组合如何,我都会得到相同的结果。
如有任何帮助,我们将不胜感激。
谢谢
最佳答案
您的解决方案取决于您希望在项目中使用哪种注释。
您可以将
@ResponseBody
添加到 Controller 中的 getSchema 方法或者,也许在您的
@RequestMapping
中添加produces
属性也可以解决这个问题。@RequestMapping(value="/schema", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE} )
最终选择,将 header 添加到您的
ResponseEntity
(这是使用此类的主要目标之一)//... HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json; charset=utf-8"); return new ResponseEntity<MyObject>(new MyObject(), headers, HttpStatus.OK);
编辑:我刚刚看到您需要 Json 和 Xml 数据,所以更好的选择是 produces
属性:
@RequestMapping(value="/schema",
method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} )
关于java.lang.AssertionError : Content type not set - Spring Controller Junit Tests 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24166167/