我正在研究Spring in Action 4的第5章示例。当我运行Test类时,我发现其中一个@Valid测试不起作用,看起来好像从未发生过验证(返回状态代码) 302的视图和视图的名称是“/ spitter / null”)。但是,当我在Tomcat中运行它时,它工作正常。
使用Maven加载validatioon jar(hibernate-validator及其依赖项)。
整个项目都在github。
有什么想法吗?
测试代码段:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={RootConfig.class, WebConfig.class})
public class SpitterControllerTest {
@Test
public void shouldFailValidationWithNoData() throws Exception {
SpitterRepository mockRepository = mock(SpitterRepository.class);
SpitterController controller = new SpitterController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller).build();
mockMvc.perform(post("/spitter/register"))
.andExpect(status().isOk())
.andExpect(view().name("registerForm"))
.andExpect(model().errorCount(5))
.andExpect(model().attributeHasFieldErrors(
"spitter", "firstName", "lastName", "username", "password", "email"));
}
}
SpitterController片段:
@RequestMapping(value="/register", method=POST)
public String processRegistration(
@Valid Spitter spitter,
Errors errors) {
if (errors.hasErrors()) {
return "registerForm";
}
spitterRepository.save(spitter);
return "redirect:/spitter/" + spitter.getUsername();
}
Spitter片段:
@NotNull
@Size(min=5, max=16)
private String username;
@NotNull
@Size(min=5, max=25)
private String password;
@NotNull
@Size(min=2, max=30)
private String firstName;
@NotNull
@Size(min=2, max=30)
private String lastName;
@NotNull
@Email
private String email;
非常感谢!
答案 0 :(得分:1)
我克隆了您的存储库,并且能够通过将您的jsp-api依赖关系更新为2.2来获得valiation的工作
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
您可能需要查看该依赖项的较新版本。使用2.1版本时,没有向ExtendedServletRequestDataBinder注册/添加验证器,或者更准确地说,SpringValidatorAdapter targetValidator为null。
根本原因是OptionalValidatorFactoryBean.afterPropertiesSet
javax.validation.ValidationException:HV000183:无法初始化 &#39; javax.el.ExpressionFactory&#39 ;.检查您是否具有EL依赖项 在类路径上,或使用ParameterMessageInterpolator而不是
我注意到您更新了shouldFailValidationWithNoData测试以使用webAppContextSetup,但仍然需要调用mock(SpitterRepository.class)
,这是不必要的。
答案 1 :(得分:1)
答案 2 :(得分:0)
将您的SpitterController
标记为@Validated
import org.springframework.validation.annotation.Validated;
@Controller
@Validated
@RequestMapping("/spitter")
public class SpitterController {
@Autowired
SpitterController
和创建MethodValidationPostProcessor bean,它委托给JSR-303
提供程序,用于对带注释的方法执行方法级验证,如下所示:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { RootConfig.class, WebConfig.class,
SpitterControllerTest.Config.class })
public class SpitterControllerTest {
@Autowired
private SpitterController spitterController;
@Configuration
public static class Config {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}
@Test
public void shouldFailValidationWithNoData() throws Exception {
}
}