前几天我遇到了一个问题,@Valid 注释被意外地从控制器类中删除了。不幸的是,它没有破坏我们的任何测试。我们的单元测试都没有真正使用 SpringAnnotationMethodHandlerAdapter
路径。我们只是直接测试我们的控制器类。
如果我的@MVC 注释错误,我如何编写单元或集成测试将正确失败?有没有一种方法可以让 Spring 使用 MockHttpServlet 或其他东西找到并使用相关的控制器?
前几天我遇到了一个问题,@Valid 注释被意外地从控制器类中删除了。不幸的是,它没有破坏我们的任何测试。我们的单元测试都没有真正使用 SpringAnnotationMethodHandlerAdapter
路径。我们只是直接测试我们的控制器类。
如果我的@MVC 注释错误,我如何编写单元或集成测试将正确失败?有没有一种方法可以让 Spring 使用 MockHttpServlet 或其他东西找到并使用相关的控制器?
我为这种事情编写集成测试。假设您有一个带有验证注释的 bean:
public class MyForm {
@NotNull
private Long myNumber;
...
}
和一个处理提交的控制器
@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";
}
}
并且您想测试 @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"));
}
当然。没有理由你的测试不能实例化它自己的DispatcherServlet
,注入它在容器中的各种项目(例如ServletContext
),包括上下文定义文件的位置。
MockXYZ
为此,Spring 附带了各种与 servlet 相关的类,包括MockServletContext
、MockHttpServletRequest
和MockHttpServletResponse
. 它们并不是通常意义上的真正“模拟”对象,它们更像是愚蠢的存根,但它们可以完成工作。
servlet 的测试上下文将具有通常的与 MVC 相关的 bean,以及要测试的 bean。初始化 servlet 后,创建模拟请求和响应,并将它们输入到 servet 的service()
方法中。如果请求被正确路由,您可以检查写入模拟响应的结果。
在即将到来的 spring 3.2(SNAPSHOT 可用)或 spring-test-mvc(https://github.com/SpringSource/spring-test-mvc)中,您可以这样做:
首先我们模拟 Validation,因为我们不想测试验证器,只想知道是否调用了验证。
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
@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();
}
}
}