10

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.

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

}

I am using: Spring 4.0.2 Junit 4.11 Gradle 1.12

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

Any help would be much appreciated.

Thanks

Community
  • 1
  • 1
blong824
  • 3,920
  • 14
  • 54
  • 75

2 Answers2

11

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

  • You can add @ResponseBody to your getSchema method in Controller

  • Or, maybe adding produces attribute in your @RequestMapping can 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);
    

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

@RequestMapping(value="/schema", 
      method = RequestMethod.GET, 
      produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} )
JR Utily
  • 1,792
  • 1
  • 23
  • 38
  • This helped, Thank You. I acutally was in the process of separating my controller into two controllers. One with the RestController annotation which adds ResponseBody to all methods and a second standard spring controller. I was referencing the wrong controller so the mockMvc.perform was returning null and the first expect was failing which is the content check. Dumb mistake but thought I'd mention it in case anyone else does the same thing. – blong824 Jun 12 '14 at 15:08
  • produces = {} did not work for me. I am using Spring 4.3.2.RELEASE. Solved with response.setHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE); – Sõber Aug 31 '16 at 11:18
  • @söber, that's strange. Do you have the `accept` header of your request well set ? – JR Utily Sep 09 '16 at 08:07
  • In another deployed app I am seeing Request headers: Accept:application/pdf and Response headers: Content-Type:text/html;charset=utf-8. In MockMVC test request has Accept=[application/pdf] and response has header Content type = null. – Sõber Sep 21 '16 at 18:56
  • The question was about json and xml, not pdf :) `produces` is a way to use different serialization (json, xml, ...) for the same data controller. There is no automatic converter for pdf, as far as I know. – JR Utily Sep 22 '16 at 16:14
  • 2
    I fixed a this error by making sure controller method doesn't return null. – brownfox May 18 '17 at 02:36
  • Above answer by @JR Utily is correct; however in my case I was using the RestController and the API was returning content type header correctly. However, I was facing above issue because I was using org.junit.jupiter.api.Test I replaced it with org.junit.Test and it worked – Vishal Jul 02 '21 at 11:13
0

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

sendon1982
  • 9,982
  • 61
  • 44