【发布时间】:2016-09-21 14:54:57
【问题描述】:
我正在与:
- Spring 框架 4.3.2
- AspectJ 1.8.9
- JUnit
- 分级
该项目基于多模块。
在src/main/java (main) 我有一些@Aspect 类,它们按预期工作。我可以通过运行时和测试确认它
现在我需要 JUnit 通过日志显示执行的 @Test 方法名称
因此在src/test/java (test) 我有以下内容:
class TestPointcut {
@Pointcut("execution(@org.junit.Test * *())")
public void testPointcut(){}
}
@Aspect
@Component
public class TestAspect {
private static final Logger logger = LoggerFactory.getLogger(TestAspect.class.getSimpleName());
@Before(value="TestPointcut.testPointcut()")
public void beforeAdviceTest(JoinPoint joinPoint){
logger.info("beforeAdviceTest - Test: {} - @Test: {}", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName() );
}
}
观察第二个类有@Aspect和@Component因此它被Spring识别
注意:我可以确认如果我写错了 @Pointcut 语法或表达式,我会出错。
问题是当我执行 @Test 方法时,对于 TestAspect 类,@Before 建议永远不会起作用。
我在 Google 进行了一项研究,发现 @Pointcut("execution(@org.junit.Test * *())") 模式是正确的。
即使我使用更明确的方式,例如:@Pointcut(value="execution(public void com.manuel.jordan.controller.persona.*Test.*Test())"),它也不起作用。
考虑我有以下Gradle
project(':web-27-rest') {
description 'Web - Rest'
dependencies {
compile project(':web-27-service-api')
testRuntime project(':web-27-aop')
testRuntime project(':web-27-aop').sourceSets.test.output
有什么遗漏或错误?
阿尔法:
一种测试类是:
- 服务器端使用
@Parameters和@ClassRule+@Rule
因此:
@RunWith(Parameterized.class)
@ContextConfiguration(classes={RootApplicationContext.class})
@Transactional
public class PersonaServiceImplTest {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE= new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
private PersonaService personaServiceImpl;
...
@Parameters
public static Collection<Persona[]> data() {
.....
});
}
...
@Test
@Sql(scripts={"classpath:....-script.sql"})
public void saveOneTest(){
....
}
其他是:
- Web 端使用 (
@WebAppConfiguration) 和:- 与
@Parameters和@ClassRule+@Rule - 没有
@Parameters和@ClassRule+@Rule
- 与
因此(在第二种方法之下):
@Transactional
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={RootApplicationContext.class, ServletApplicationContext.class})
public class PersonaDeleteOneControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
private ResultActions resultActions;
...
@BeforeClass
public static void setUp_(){
...
}
@Before
public void setUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void deleteOneHtmlGetTest() throws Exception {
【问题讨论】:
-
你能在这里提供你的测试类代码吗?
-
您好 @SergeyBespalov 代码已更新,请参阅
Alpha部分。谢谢! -
你可以尝试为你的测试类添加
@EnableAspectJAutoProxy(proxyTargetClass=true)注解。 -
你好@SergeyBespalov,它不起作用。似乎“缺少”其他东西
-
您使用的是哪种编织方式?是spring aop代理吗?
标签: junit aop aspectj spring-aop