Java.lang.AssertionError: Content Type Not Set - Spring Junit Tests Controller

I am trying to run some unit tests on my controllers. No matter what I do, all controller tests are returned

java.lang.AssertionError: Content type not set

I test methods return json and xml data.

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

   }

}

unit test is configured as follows:

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 use: Spring 4.0.2 Junit 4.11 Gradle 1.12

I saw the SO Similiar Question , but no matter what combination of contentType to expect in my unit test, I get the same result.

Any help would be greatly appreciated.

thank

+4
source share
2 answers

, .

  • @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 AND Xml Data, produces:

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

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

<mvc:annotation-driven /> xml @EnableWebMvc

0

Source: https://habr.com/ru/post/1544182/


All Articles