我很难过.我正在尝试测试一个AspectJ类.当我运行我的应用程序时,我的Aspect类被完美地拾取.但是,我似乎无法让任何Aspect类拦截测试中的任何方法.
我使用的是Spring 3.2.2,AspectJ 1.7.2和Maven 4.
这是我正在使用的简单测试:
测试AspectJ类
package my.package.path.config;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Aspect
public class TestAOP {
private String message;
public TestAOP() {
}
@Pointcut("execution(* my.package.path.TestAOPClient.relayMessage(..))")
public void aopPointcut() {
}
@Around("aopPointcut()")
public String monitor(ProceedingJoinPoint pjp) throws Throwable {
String msg = (String)pjp.proceed();
this.setMessage(msg);
return msg;
}
}
正在拦截其方法的类
package my.package.path.config;
public class TestAOPClient {
public String relayMessage(String msg) {
return msg;
}
}
测试类
package my.package.path.config;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@Configuration
@ContextConfiguration(classes={WebConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/main/java")
public class AopConfigTest extends AbstractJUnit4SpringContextTests {
@Bean
public TestAOP testAop() throws Exception {
return new TestAOP();
}
@Test
public void assertTestConfigIsActive() {
TestAOPClient client = new TestAOPClient();
client.relayMessage("hello");
assertThat(((TestAOP)applicationContext.getBean("testAop")).getMessage(), equalTo("hello"));
}
}
WebConfig文件
package my.package.path.web.context;
@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy(proxyTargetClass=false)
@ComponentScan(value={"my.package.path.config", "my.package.path.web"})
public class WebConfig {
}
总是,我会得到断言错误
Expected: "hello" but: was null
我的WebApplicationContext似乎被选中,因为在运行时,如果我指定一个不存在我的Aspect切入点的类,我将得到一个ApplicationContext无法加载错误.
我错过了什么?