考虑使用Spring 3.2及其mvc-test-
framework
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml")public class WebMvcTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void getFoo() throws Exception { this.mockMvc.perform( get("/testx") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) ) .andExpect(status().isUnauthorized()); }}控制器代码
@Controllerpublic class MyController { public class MyException extends RuntimeException { }; @RequestMapping("/testx") public void myMethod() { throw new MyException(); } @ExceptionHandler(MyException.class) @ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "blah") public void handler() { System.out.println("handler processed"); }}此“测试”顺利通过。
免责声明:目前,我在Spring MVC测试中是菜鸟,实际上这是我的第一个测试。
upd:



