9

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

java.lang.AssertionError: Content type not set

我正在测试这些方法是否返回 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);

   }

}

单元测试设置如下:

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 Junit 4.11 Gradle 1.12

我已经看过 SO question Similiar Question但无论在我的单元测试中 contentType 和 expect 的组合如何,我都会得到相同的结果。

任何帮助将非常感激。

谢谢

4

2 回答 2

10

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

  • 您可以添加@ResponseBody到控制器中的 getSchema 方法

  • 或者,也许produces在你的中添加属性@RequestMapping也可以解决它。

    @RequestMapping(value="/schema", 
          method = RequestMethod.GET, 
          produces = {MediaType.APPLICATION_JSON_VALUE} )
    
  • 最终选择,将标题添加到您的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} )
于 2014-06-11T21:50:19.900 回答
0

您需要添加

@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, 
method = RequestMethod.GET
value = "/schema")

<mvc:annotation-driven />您的 xml 配置中或@EnableWebMvc

于 2016-12-30T05:37:56.377 回答