考虑使用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());
}
}
控制器代码
@Controller
public 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测试中是菜鸟,实际上这是我的第一个测试。