2014-09-05 115 views
3

我有以下控制器:写JUnit测试本地@ExceptionHandler

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) {} 
} 

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

+0

因为这是你的设置。如果您想要设置完整的应用程序上下文,您只需测试控制器而不是剩余的基础架构。 – 2014-09-05 13:42:24

+0

注意'standaloneSetup'。检查其他'MockMvcBuilders'方法。 – 2014-09-05 14:48:33

回答

2

当您使用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覆盖一个越来越困难的情况下(上一类使用@ControllerAdvice例外类其中包含@ExceptionHandler)。

+0

谢谢,我试过你的方法。但不幸的是,我得到以下错误:org.springframework.web.util.NestedServletException:请求处理失败;嵌套的异常是java.lang.NullPointerException – fashuser 2014-09-05 15:11:34

+0

@fashuser这很奇怪!我运行这个代码,一切都按预期工作!你能用这个信息更新你的问题吗? – geoand 2014-09-05 15:12:40

+0

我已经添加了完整的堆栈跟踪问题。 – fashuser 2014-09-05 15:22:08

0

您的班级net.scansafe.scancentre21.springmvc.web.easyid.ManageSamlAuthenticationRealmController.verifySecondarySamlSpCertificate(ManageSamlAuthenticationRealmController.java)中的某个房产为空。

您可以调试类的方法来找到它。你需要添加一个@Autowired注入这个属性。