Bra*_*ugh 9 java spring unit-testing spring-mvc spring-annotations
前几天我遇到了一个问题,其中一个@Valid注释被意外地从控制器类中删除了.不幸的是,它没有破坏我们的任何测试.我们的单元测试都没有实际运行Spring AnnotationMethodHandlerAdapter路径.我们直接测试我们的控制器类.
如果我的@MVC注释错误,我该如何编写一个正确失败的单元或集成测试?有没有办法我可以让Spring找到并使用MockHttpServlet查找和运用相关的控制器?
sca*_*a05 13
我为这种事写了集成测试.假设你有一个带有验证注释的bean:
public class MyForm {
@NotNull
private Long myNumber;
...
}
Run Code Online (Sandbox Code Playgroud)
以及处理提交的控制器
@Controller
@RequestMapping("/simple-form")
public class MyController {
private final static String FORM_VIEW = null;
@RequestMapping(method = RequestMethod.POST)
public String processFormSubmission(@Valid MyForm myForm,
BindingResult result) {
if (result.hasErrors()) {
return FORM_VIEW;
}
// process the form
return "success-view";
}
}
Run Code Online (Sandbox Code Playgroud)
并且您想测试@Valid和@NotNull注释是否正确连接:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"file:web/WEB-INF/application-context.xml",
"file:web/WEB-INF/dispatcher-servlet.xml"})
public class MyControllerIntegrationTest {
@Inject
private ApplicationContext applicationContext;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HandlerAdapter handlerAdapter;
@Before
public void setUp() throws Exception {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
}
ModelAndView handle(HttpServletRequest request, HttpServletResponse response)
throws Exception {
final HandlerMapping handlerMapping = applicationContext.getBean(HandlerMapping.class);
final HandlerExecutionChain handler = handlerMapping.getHandler(request);
assertNotNull("No handler found for request, check you request mapping", handler);
final Object controller = handler.getHandler();
// if you want to override any injected attributes do it here
final HandlerInterceptor[] interceptors =
handlerMapping.getHandler(request).getInterceptors();
for (HandlerInterceptor interceptor : interceptors) {
final boolean carryOn = interceptor.preHandle(request, response, controller);
if (!carryOn) {
return null;
}
}
final ModelAndView mav = handlerAdapter.handle(request, response, controller);
return mav;
}
@Test
public void testProcessFormSubmission() throws Exception {
request.setMethod("POST");
request.setRequestURI("/simple-form");
request.setParameter("myNumber", "");
final ModelAndView mav = handle(request, response);
// test we're returned back to the form
assertViewName(mav, "simple-form");
// make assertions on the errors
final BindingResult errors = assertAndReturnModelAttributeOfType(mav,
"org.springframework.validation.BindingResult.myForm",
BindingResult.class);
assertEquals(1, errors.getErrorCount());
assertEquals("", errors.getFieldValue("myNumber"));
}
Run Code Online (Sandbox Code Playgroud)
请参阅我关于集成测试Spring的MVC注释的博客文章
在即将推出的 spring 3.2(可用快照)或使用 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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我们的测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6681 次 |
| 最近记录: |