java – 为@ExceptionHandler编写JUnit测试

前端之家收集整理的这篇文章主要介绍了java – 为@ExceptionHandler编写JUnit测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 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,实际上是我的第一个测试.
upd:感谢Drake for the correction.

原文链接:https://www.f2er.com/java/125556.html

猜你在找的Java相关文章