为@ExceptionHandler编写JUnit测试

我正在使用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。

回答:

考虑使用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测试中是菜鸟,实际上这是我的第一个测试。

以上是 为@ExceptionHandler编写JUnit测试 的全部内容, 来源链接: utcz.com/qa/416842.html

回到顶部