2
我有一個Spring MVC的應用程序,我用一個方面捕獲異常所有控制器方法如何在Spring MVC應用程序
@Component
@Aspect
public class ControllerExceptionAspect {
private Logger logger;
public ControllerExceptionAspect() {
logger = Logger.getLogger(ControllerExceptionAspect.class);
}
public ControllerExceptionAspect(Logger logger) {
this.logger = logger;
}
// Catching all exceptions from all methods in all controllers classes
@AfterThrowing(pointcut = "execution(* com.my.package..controller..*(..))", throwing = "exception")
public void afterThrowingAdvice(Exception exception) {
logger.error("CONTROLLER ASPECT: EXCEPTION IN METHOD -> " +
exception.getClass());
}
}
看點工作正常,但可惜的是,我不能測試它測試看點。我試過很多次,但不能得到如何捕捉一方面方法中是否叫我模擬控制器異常後
@SuppressWarnings("ALL")
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(classes = RootConfig.class),
@ContextConfiguration(classes = WebConfig.class)
})
public class ControllerExceptionAspectTest {
@Autowired
ApplicationContext applicationContext;
@Test
public void testControllerExceptionAspectGetsExecutedWhenExceptionOccures(){
HomeController homeController = (HomeController)applicationContext.getAutowireCapableBeanFactory().getBean("homeController");
try{homeController.callMethod("00000");}
catch (Exception e){}
ControllerExceptionAspect controllerExceptionAspect = (ControllerExceptionAspect)applicationContext.getAutowireCapableBeanFactory().getBean("controllerExceptionAspect");
// HOW TO CATCH THAT ASPECT METHOD WAS CALLED???
}
}
作爲[Spring文檔(http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-pointcuts-designators)說,如果你將使用完整的AspectJ而不是Spring AOP,你可以在你的測試中使用像'adviceexecution()'這樣的切入點。 – kriegaex