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.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...