编写本地 @ExceptionHandler 的 JUnit 测试

4
我可以帮您翻译成中文。以下是您提供的控制器代码:

我有以下控制器:

class Controller {

    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/verifyCert", method = RequestMethod.GET)
    public void verifyCertificate() throws CertificateExpiredException, CertificateNotYetValidException {
        certificate.checkValidity();
    }

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler({CertificateExpiredException.class, CertificateNotYetValidException.class})
    public void handleCertificateValidityException(Exception e) {}
}

我的目标是,如果证书无效,控制器将重定向到异常处理程序。


1
因为这是您设置的内容。您只测试了控制器,而没有测试其余基础设施,如果您想要测试其余基础设施,需要设置完整的应用程序上下文。 - M. Deinum
η·Ζφ≥®φ³è standaloneSetupψIJφüΞ〴εÖΕδΜ• MockMvcBuilders φ•Ιφ≥ïψIJ - Sotirios Delimanolis
3个回答

3
使用 standaloneSetup 时,你所做的只是为特定控制器执行设置。
如果你不想配置整个应用程序上下文(使用 webAppContextSetup 而不是 standaloneSetup),你可以通过更改代码手动设置异常处理程序:
 @Before
 public void setup() throws IOException {
     MockitoAnnotations.initMocks(this);
     mockMvc = MockMvcBuilders.standaloneSetup(controller).setHandlerExceptionResolvers(new ExceptionHandlerExceptionResolver()).build();
 }

 @Test
 public void test() throws Exception {
     mockMvc.perform(get("/verifyCert.controller").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andExpect(status().isForbidden());
 }

这是可行的,因为ExceptionHandlerExceptionResolver是Spring MVC用来处理基于@ExceptionHandler注释的异常的类。
请查看one中我较早的相关答案之一,涵盖了更加困难的情况(在包含@ExceptionHandler的类上使用@ControllerAdvice)。

谢谢,我尝试了你的方法。但不幸的是,我得到了以下错误:org.springframework.web.util.NestedServletException: 请求处理失败;嵌套异常是java.lang.NullPointerException。 - fashuser
@fashuser 这很奇怪!我运行了这段代码,一切都按预期工作了!你能更新一下你的问题吗? - geoand
我已经在问题中添加了完整的堆栈跟踪。 - fashuser
@fashuser 你使用的 Spring 版本是哪个? - geoand
@fashuser 我无法在Spring 4或Spring 3.2中复现您的问题。 - geoand

-1
我是这样解决的:
@Test(expected=MyException.class)
public void shouldThrowException() throws IOException, Exception {

    //Mock Response Controller 
    when(client.mymethod(any(MyInputClassOfController.class)))
        .thenReturn(mockedResponse);

    when(innerClassInController.myMethodThatInvokeTheException(mock(MyClass.class)))
        .thenThrow(new MyException("message"));

    this.mockMvc.perform(post("/root/search/")
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .content( "null Request to throw the exception"))
        .andExpect(status().isBadRequest());
}

-1

您的类中的属性 net.scansafe.scancentre21.springmvc.web.easyid.ManageSamlAuthenticationRealmController.verifySecondarySamlSpCertificate(ManageSamlAuthenticationRealmController.java) 为空。

您可以调试该类的方法以找到它。您需要为此属性添加 @Autowired 进行注入。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接