为@ExceptionHandler编写 JUnit 测试
2022-09-04 22:34:35
我正在使用Spring MVC编写Rest服务。以下是该类的大纲:
@Controller
public class MyController{
@RequestMapping(..)
public void myMethod(...) throws NotAuthorizedException{...}
@ExceptionHandler(NotAuthorizedException.class)
@ResponseStatus(value=HttpStatus.UNAUTHORIZED, reason="blah")
public void handler(...){...}
}
我已经使用这里发布的设计编写了我的单元测试。测试基本如下:
@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。