Reputation: 1999
I have set up a simple Spring REST method in a class which should just return the text that was sent to it in a POST request as a response. My method in class MyService.java:
@RequestMapping(value = "/my/url", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> myMethod(@RequestBody final String body) {
return new ResponseEntity<String>(body, HttpStatus.OK);
}
I have a unit test which uses Spring's MockMvc to test the method:
@Autowired
private MyService service;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
mockMvc = standaloneSetup(service).build();
}
@Test
public void myTest() throws Exception {
Assert.assertNotNull(service); // Class has been instantiated
final String content = "Hello world";
final String url = "/my/url";
final MvcResult result = mockMvc.perform(post(url) //
.content(content) //
.accept(MediaType.TEXT_PLAIN_VALUE)) //
.andExpect(status().isOk()) //
.andReturn();
}
The test fails with a message "Status expected:<200> but was:<415>" on the perform() line of the unit test. In the console, I can see this message:
Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'null' not supported
415 is a "content not supported" error.
Spring version 4.1.7.
Any suggestions as to what I am doing wrong? Thanks in advance.
Upvotes: 0
Views: 1153
Reputation: 1999
Fixed. Missing the content type when performing the POST. I added this to the test and it worked successfully:
.header("Content-Type", MediaType.TEXT_PLAIN_VALUE)
Upvotes: 1