java.lang.AssertionError:未设置内容类型 - Spring Controller Junit Tests

blo*_*824 8 java junit spring spring-mvc mockmvc

我正在尝试在我的控制器上进行一些单元测试.无论我做什么,所有控制器测试都会返回

java.lang.AssertionError: Content type not set
Run Code Online (Sandbox Code Playgroud)

我正在测试这些方法返回json和xml数据.

以下是控制器的示例:

@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);

   }

}
Run Code Online (Sandbox Code Playgroud)

单元测试设置如下:

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));
}
Run Code Online (Sandbox Code Playgroud)

}

我正在使用:Spring 4.0.2 Junit 4.11 Gradle 1.12

我已经看到了SO问题类似问题,但无论contentType和期望在我的单元测试中得到了相同的结果.

任何帮助将非常感激.

谢谢

JR *_*ily 10

您的解决方案取决于您要在项目中使用的注释类型.

  • 您可以@ResponseBody在Controller中添加到getSchema方法

  • 或者,也许添加produces属性@RequestMapping也可以解决它.

    @RequestMapping(value="/schema", 
          method = RequestMethod.GET, 
          produces = {MediaType.APPLICATION_JSON_VALUE} )
    
    Run Code Online (Sandbox Code Playgroud)
  • 最后选择,为您添加标题ResponseEntity(这是使用此类的主要目标之一)

    //...
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=utf-8");
    return new ResponseEntity<MyObject>(new MyObject(), headers, HttpStatus.OK);
    
    Run Code Online (Sandbox Code Playgroud)

编辑:我刚刚看到你想要Json和Xml数据,所以更好的选择是produces属性:

@RequestMapping(value="/schema", 
      method = RequestMethod.GET, 
      produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} )
Run Code Online (Sandbox Code Playgroud)

  • 我通过确保控制器方法不返回null来修复此错误. (2认同)