spring mockMVC,现在得到正确的错误消息 MethodArgumentNotValidException 抛出
spring mock MVC ,getting the right error message now MethodArgumentNotValidExceptionis thrown
我的短语是检查我的控制器,它如何序列化异常,而我正在使用 javax.validation
( JSR 380 )
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-context-test.xml"})
@WebAppConfiguration
public class MyDTOControllerIT {
private MockMvc mockMvc;
@Mock private MyService myService;
@Mock private MyDTOService myDTOService;
private ObjectMapper objectMapper;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc =
MockMvcBuilders.standaloneSetup(MyController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers(
(ViewResolver) (viewName, locale) -> new MappingJackson2JsonView())
.build();
objectMapper = new CustomObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
@Test
public void create_Illegal() throws Exception {
W req;
try (InputStream jsonInputStream1 =
this.getClass().getResourceAsStream(IILEGAL_REQ_BODY)) {
req = objectMapper.readValue(jsonInputStream1, MyDto.class);
}
mockMvc
.perform(
MockMvcRequestBuilders.post(
"/v1/somthing")
.content(objectMapper.writeValueAsString(req))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(containsString("\"pid\":123456")))
.andDo(MockMvcResultHandlers.print());
}
}
dto
public class W{
@NotNull(message = "xxxxxx") private String name;
}
class MyDTOController ...
@PostMapping(value = "/v1/somthing")
@RequestBody @Validated W value){
}
所以我希望W被侵犯...
这是我的测试环境
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:component-scan
base-package="my.package">
<context:annotation-config/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
<mvc:argument-resolvers>
<ref bean="sortResolver"/>
<ref bean="pageableResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
<bean id="objectMapper" class="my.package.CustomObjectMapper"/>
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource"
p:basenames="WEB-INF/i18n/messages" p:fallbackToSystemLocale="false"/>
<context:exclude-filter type="assignable"
expression="my.package.MyDTOController"/>
我最后得到的是
Resolved Exception:
Type = org.springframework.web.bind.MethodArgumentNotValidException
MockHttpServletResponse:
Status = 400
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null Redirected URL = null
我拥有所有正确的验证器依赖项
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<hibernate-validator.version>4.1.0.Final</hibernate-validator.version>
我也有
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler
正在扫描的(存在于my.package
)
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
有
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request)
当我在那里放置一个断点时,它没有被捕获,
如何获得正确的错误消息?
mockMvc =
MockMvcBuilders.standaloneSetup(MyController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers((ViewResolver) (viewName, locale) -> new MappingJackson2JsonView())
.setControllerAdvice(controllerExceptionHandler)
.build();
.setControllerAdvice(controllerExceptionHandler)
解决了。
我的短语是检查我的控制器,它如何序列化异常,而我正在使用 javax.validation
( JSR 380 )
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-context-test.xml"})
@WebAppConfiguration
public class MyDTOControllerIT {
private MockMvc mockMvc;
@Mock private MyService myService;
@Mock private MyDTOService myDTOService;
private ObjectMapper objectMapper;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc =
MockMvcBuilders.standaloneSetup(MyController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers(
(ViewResolver) (viewName, locale) -> new MappingJackson2JsonView())
.build();
objectMapper = new CustomObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
@Test
public void create_Illegal() throws Exception {
W req;
try (InputStream jsonInputStream1 =
this.getClass().getResourceAsStream(IILEGAL_REQ_BODY)) {
req = objectMapper.readValue(jsonInputStream1, MyDto.class);
}
mockMvc
.perform(
MockMvcRequestBuilders.post(
"/v1/somthing")
.content(objectMapper.writeValueAsString(req))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(containsString("\"pid\":123456")))
.andDo(MockMvcResultHandlers.print());
}
}
dto
public class W{
@NotNull(message = "xxxxxx") private String name;
}
class MyDTOController ...
@PostMapping(value = "/v1/somthing")
@RequestBody @Validated W value){
}
所以我希望W被侵犯...
这是我的测试环境
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:component-scan
base-package="my.package">
<context:annotation-config/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
<mvc:argument-resolvers>
<ref bean="sortResolver"/>
<ref bean="pageableResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
<bean id="objectMapper" class="my.package.CustomObjectMapper"/>
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource"
p:basenames="WEB-INF/i18n/messages" p:fallbackToSystemLocale="false"/>
<context:exclude-filter type="assignable"
expression="my.package.MyDTOController"/>
我最后得到的是
Resolved Exception: Type = org.springframework.web.bind.MethodArgumentNotValidException
MockHttpServletResponse: Status = 400 Error message = null Headers = {} Content type = null Body = Forwarded URL = null Redirected URL = null
我拥有所有正确的验证器依赖项
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<hibernate-validator.version>4.1.0.Final</hibernate-validator.version>
我也有
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler
正在扫描的(存在于my.package
)
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
有
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request)
当我在那里放置一个断点时,它没有被捕获,
如何获得正确的错误消息?
mockMvc =
MockMvcBuilders.standaloneSetup(MyController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers((ViewResolver) (viewName, locale) -> new MappingJackson2JsonView())
.setControllerAdvice(controllerExceptionHandler)
.build();
.setControllerAdvice(controllerExceptionHandler)
解决了。