为@ExceptionHandler编写JUnit测试

Joh*_*n B 11 java rest junit spring spring-mvc

我正在使用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(...){...}
 }
Run Code Online (Sandbox Code Playgroud)

我使用此处发布的设计编写了单元测试.测试基本如下:

@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()));
}

}
Run Code Online (Sandbox Code Playgroud)

然而,召唤handle是扔了NotAuthorizedException.我已经读过,这是设计能够单元测试方法抛出相应的异常,但是我想编写一个自动化测试,框架正在适当地处理这个异常,并且被测试的类已经适当地实现了处理程序.有没有办法做到这一点?

请注意,我无法在可以发布的地方访问实际代码.

另外,我受限于(出于不幸的原因)Spring 3.0.5或3.1.2.

Bor*_*hov 7

考虑使用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());
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器代码

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这个"测试"顺利通过.

免责声明:目前我是Spring MVC测试中的菜鸟,实际上这是我的第一次测试.
upd:感谢The Drake 的纠正.