java.lang.AssertionError: Content type not set - Spring Controller Junit Tests

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24166167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:34:47  来源:igfitidea点击:

java.lang.AssertionError: Content type not set - Spring Controller Junit Tests

javaspringspring-mvcjunitmockmvc

提问by blong824

I am trying to do some unit testing on my controllers. No matter what I do all controller tests return

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

java.lang.AssertionError: Content type not set

I am testing that the methods return json and xml data.

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

Here is an example of the 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);

   }

}

The unit test is set up like this:

单元测试设置如下:

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 MappingHymanson2HttpMessageConverter(),
                        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));
}

}

}

I am using: Spring 4.0.2 Junit 4.11 Gradle 1.12

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

I have seen the SO question Similiar Questionbut no matter what combination of contentType and expect in my unit test I get the same result.

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

Any help would be much appreciated.

任何帮助将非常感激。

Thanks

谢谢

采纳答案by JR Utily

Your solution depends on what kinds of annotation you want to use in your project.

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

  • You can add @ResponseBodyto your getSchema method in Controller

  • Or, maybe adding producesattribute in your @RequestMappingcan solve it too.

    @RequestMapping(value="/schema", 
          method = RequestMethod.GET, 
          produces = {MediaType.APPLICATION_JSON_VALUE} )
    
  • Final choice, add headers to your ResponseEntity(which is one of the main objective of using this class)

    //...
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=utf-8");
    return new ResponseEntity<MyObject>(new MyObject(), headers, HttpStatus.OK);
    
  • 您可以添加@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);
    

Edit : I've just seen you want Json AND Xml Data, so the better choice would be the producesattribute:

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

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

回答by sendon1982

You need to add

你需要添加

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

And <mvc:annotation-driven />in your xml config or @EnableWebMvc

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