在即将发布的spring 3.2(可用的SNAPSHOT)中或通过spring-test-
mvc(https://github.com/SpringSource/spring-test-mvc),您可以这样做:
首先我们模拟验证,因为我们不想测试验证器,只是想知道是否调用了验证。
public class LocalValidatorFactoryBeanMock extends LocalValidatorFactoryBean{ private boolean fakeErrors; public void fakeErrors ( ) { this.fakeErrors = true; } @Override public boolean supports ( Class<?> clazz ) { return true; } @Override public void validate ( Object target, Errors errors, Object... validationHints ) { if (fakeErrors) { errors.reject("error"); } }}
这是我们的测试班:
@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@ContextConfigurationpublic class RegisterControllerTest{ @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Autowired @InjectMocks private RegisterController registerController; @Autowired private LocalValidatorFactoryBeanMock validator; @Before public void setup ( ) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); // if you want to inject mocks into your controller MockitoAnnotations.initMocks(this); } @Test public void testPostValidationError ( ) throws Exception { validator.fakeErrors(); MockHttpServletRequestBuilder post = post("/info/register"); post.param("name", "Bob"); ResultActions result = getMockMvc().perform(post); // no redirect as we have errors result.andExpect(view().name("info/register")); } @Configuration @import(DispatcherServletConfig.class) static class Config extends WebMvcConfigurerAdapter { @Override public Validator getValidator ( ) { return new LocalValidatorFactoryBeanMock(); } @Bean RegisterController registerController ( ) { return new RegisterController(); } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)