java – 为@ExceptionHandler编写JUnit测试
发布时间:2020-12-14 16:23:00 所属栏目:Java 来源:网络整理
导读:我正在使用 Spring MVC编写休息服务.这是课程的大纲: @Controller public class MyController{ @RequestMapping(..) public void myMethod(...) throws NotAuthorizedException{...} @ExceptionHandler(NotAuthorizedException.class) @ResponseStatus(valu
我正在使用
Spring MVC编写休息服务.这是课程的大纲:
@Controller public class MyController{ @RequestMapping(..) public void myMethod(...) throws NotAuthorizedException{...} @ExceptionHandler(NotAuthorizedException.class) @ResponseStatus(value=HttpStatus.UNAUTHORIZED,reason="blah") public void handler(...){...} } 我写了我的单元测试使用设计发布了here.测试基本如下: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(....) public class mytest{ MockHttpServletRequest requestMock; MockHttpServletResponse responseMock; AnnotationMethodHandlerAdapter handlerAdapter; @Before public void setUp() { requestMock = new MockHttpServletRequest(); requestMock.setContentType(MediaType.APPLICATION_JSON_VALUE); requestMock.addHeader(HttpHeaders.ACCEPT,MediaType.APPLICATION_JSON_VALUE); responseMock = new MockHttpServletResponse(); handlerAdapter = new AnnotationMethodHandlerAdapter(); } @Test public void testExceptionHandler(){ // setup .... handlerAdapter.handle(...); // verify // I would like to do the following assertThat(responseMock.getStatus(),is(HttpStatus.UNAUTHORIZED.value())); } } 但是,对handle的调用是抛出NotAuthorizedException.我已经读过这个设计是为了能够单元测试该方法抛出适当的异常,但是我想编写一个自动测试,该框架正确地处理这个异常,并且被测试类正确地实现了处理程序.有没有办法做到这一点? 请注意,我无法访问我可以发布的地方的实际代码. 此外,我对Spring 3.0.5或3.1.2有限(不幸的是). 解决方法
考虑使用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测试中的noob,实际上是我的第一个测试. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |