Moved MediaTypeNotAcceptableException article from spring-mvc-java to spring-mvc-basics module, and added test
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.exception;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.HttpMediaTypeNotAcceptableException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@ControllerAdvice
|
||||
public class HttpMediaTypeNotAcceptableExceptionExampleController {
|
||||
|
||||
@PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Map<String, String> test() {
|
||||
return Collections.singletonMap("key", "value");
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
|
||||
public String handleHttpMediaTypeNotAcceptableException() {
|
||||
return "acceptable MIME type:" + MediaType.APPLICATION_JSON_VALUE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.exception;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import com.baeldung.Application;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
@AutoConfigureMockMvc
|
||||
public class HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void whenHttpMediaTypeNotAcceptableExceptionTriggered_thenExceptionHandled() throws Exception {
|
||||
mockMvc.perform(post("/test").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_PDF))
|
||||
.andExpect(content().string("acceptable MIME type:application/json"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user