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
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} )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With