Spring Aspect不在测试环境中运行

时间:2014-03-28 04:01:27

标签: java spring integration-testing spring-aop

在我的网络系统中,我有一个AppConfig这样的课程

@Configuration
@ComponentScan(basePackages = "com.mypackage")
@EnableWebMvc
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AppConfig {

    @Bean
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }
}

我还创建了Aspect类,以便在用户触发请求时检查身份验证

@Component
@Aspect
public class AuthenticationAspect {
    @Before(value = "@within(com.mypackage.logic.aspects.SessionLookUp) || @annotation(com.mypackage.logic.aspects.SessionLookUp)")
    public void before(JoinPoint joinPoint) throws FailAuthenticationException {
        LogFactory.getLog(AuthenticationAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());

        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session = attr.getRequest().getSession(true);

        String username     = (String)  session.getAttribute("username");
        String role         = (String)  session.getAttribute("role");
        Boolean isLogined   = (Boolean) session.getAttribute("isLogined");

        if (
                session     == null || 
                username    == null || username.isEmpty()   ||
                role        == null || role.isEmpty()       ||
                isLogined   == null
        ) {
            throw new FailAuthenticationException("You need to login first");
        }

    }

    @After(value = "@within(com.mypackage.logic.aspects.SessionLookUp) || @annotation(com.mypackage.logic.aspects.SessionLookUp)")
    public void after(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(AuthenticationAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }
}

使用SessionLookup界面

@Component
@Target(value = { ElementType.METHOD, ElementType.TYPE })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface SessionLookUp {}

这是我的控制器

@Controller
public class ApplicationController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    @SessionLookUp
    public String sayHello() {
            return "Hello";
    }
}

现在,当我在浏览器上运行时,我将收到消息"您需要先登录",但在使用集成测试时,测试将通过{{1}没有说什么

Aspect

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您的@ContextConfiguration被声明为

@ContextConfiguration(classes = {
    ApplicationController.class,
    AuthenticationAspect.class,
    DatabaseConfig.class 
})

您似乎缺少声明Aspect配置的AppConfig类。

请注意,您应该删除ApplicationControllerAuthenticationAspect以及AppConfig包含(和管理)的内容。