问题
I am using the Gradle AspectJ plugin to weave some production aspect into test Java code. I would have expected this to work out of the box with the plugin, but apparently that's not the case as demoed here: https://github.com/sedubois/gradle-aspectj-poc/tree/dc44f529831a485fcff8f4889dba8098784dddb4
The weaving of UnsupportedOperationAspect into MainSevice (both under src/main/java) works, but the weaving of this same aspect into TestService (under src/test/java) doesn't.
I am new to Groovy, Gradle and AspectJ and didn't figure out if I should add some testAspectpath configuration or similar?
EDIT1: seems unrelated, but iajc gives a warning:
...
:compileTestAspect
[ant:iajc] [warning] incorrect classpath: [...]\gradle-aspectj-poc\build\resources\main
...
EDIT2: I naively added this code to the Gradle dependencies:
ajInpath fileTree(dir: "src/test/java")
aspectpath fileTree(dir: "src/test/java")
testAjInpath fileTree(dir: "src/test/java")
testAspectpath fileTree(dir: "src/test/java")
It doesn't help, the first test works and the second one fails as usual, with these new messages:
...
:compileAspect
[ant:iajc] [warning] build config error: skipping missing, empty or corrupt aspectpath entry: [...]\gradle-aspectj-poc\src\test\java\com\hello\aop\TestService.java
[ant:iajc] [warning] build config error: skipping missing, empty or corrupt inpath entry: [...]\gradle-aspectj-poc\src\test\java\com\hello\aop\TestService.java
...
:compileTestAspect
[ant:iajc] [warning] build config error: skipping missing, empty or corrupt aspectpath entry: [...]\gradle-aspectj-poc\src\test\java\com\hello\aop\TestService.java
[ant:iajc] [warning] build config error: skipping missing, empty or corrupt inpath entry: [...]\gradle-aspectj-poc\src\test\java\com\hello\aop\TestService.java
[ant:iajc] [warning] incorrect classpath: [...]\gradle-aspectj-poc\build\resources\main
...
回答1:
By default the plugin does not weave the main aspects in the test classes - we simply never made a configuration option for it. You can do this yourself using the following line:
testAspectpath sourceSets.main.output
回答2:
There is no expression matching TestService#serviceMethod().
In order to make your testcase work you need to advice your service method and (very important) the aspect must be located in the src/test/ package. Otherwise the compiler would not weave it in.
// located in `src/test/java`
package com.hello.aop;
@Aspect
class UnsupportedOperationAspect {
@Before("execution(void com.hello.aop.TestService.serviceMethod(..))")
public void throwUnsupportedOperationOnMethod1() {
throw new UnsupportedOperationException();
}
}
Just a sidenote as i do not know what you are trying to achieve by advising test-classes (that are components specifically for test cases only): keep your tests as simple as possible.
来源:https://stackoverflow.com/questions/29476081/weaving-production-aspect-into-test-class-with-gradle-aspectj