Moved MediaTypeNotAcceptableException article from spring-mvc-java to spring-mvc-basics module, and added test

This commit is contained in:
Gerardo Roza
2019-07-15 13:07:01 -03:00
parent fc24c7b69b
commit 3150b6d4fd
4 changed files with 37 additions and 5 deletions

View File

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

View File

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