我有几个AspectJ策略执行方面应用于我的Maven src / main / java目录。最近,已经发现了这些方面的一些漏洞,所以我想为它们创建单元测试。
我想要做的是在测试目录中创建Java文件(不是由AspectJ编译的),然后以编程方式在所选文件上调用AspectJ编译器并根据结果进行断言。
这样的事情会很完美:
assertThat("MyJavaClass.java", producesCompilerErrorFor("SomeAspect.aj"));
有人做过类似的事吗?
答案 0 :(得分:4)
像往常一样,这是我自己的答案:
我创建了一个名为AbstractAspectJPolicyEnforcementTest
的类。一些内容是专有信息,但我会向您展示最重要的内容:
protected Matcher<File> producesCompilationErrorWith(final File aspectFile) {
return new AspectJCompilationMatcher(aspectFile, Result.ERROR);
}
private class AspectJCompilationMatcher extends TypeSafeMatcher<File> {
private final File aspectFile;
private final Result expectedResult;
private Result result;
public AspectJCompilationMatcher(final File aspectFile, final Result expectedResult) {
this.aspectFile = aspectFile;
this.expectedResult = expectedResult;
}
@Override
protected boolean matchesSafely(final File javaSourceFile) {
result = compile(javaSourceFile, aspectFile);
return result == expectedResult;
}
@Override
public void describeTo(final Description description) {
description.appendText("compilation result: ").appendValue(result);
}
}
enum Result {
ERROR,
WARNING,
SUCCESS
}
private Result compile(final File javaFileName, final File aspectFile) {
assertExists(javaFileName);
assertExists(aspectFile);
List<String> argList = newArrayList();
// java 7 compatibility
argList.add("-source");
argList.add("1.7");
argList.add("-target");
argList.add("1.7");
// set class path
argList.add("-cp");
argList.add(System.getProperty("java.class.path"));
// add java file
argList.add(javaFileName.getAbsolutePath());
// add aspect files
argList.add(aspectFile.getAbsolutePath());
for (File additionalAspectFile : requiredAspects) {
assertExists(additionalAspectFile);
argList.add(additionalAspectFile.getAbsolutePath());
}
String[] args = argList.toArray(new String[argList.size()]);
List<String> fails = newArrayList();
List<String> errors = newArrayList();
List<String> warnings = newArrayList();
List<String> infos = newArrayList();
// org.aspectj.tools.ajc.Main;
Main.bareMain(args, false, fails, errors, warnings, infos);
if (!fails.isEmpty() || !errors.isEmpty()) {
return Result.ERROR;
} else if (!warnings.isEmpty()) {
return Result.WARNING;
} else {
return Result.SUCCESS;
}
}
以下是我在测试类中使用它的方法:
public class ForbiddenPackageNameAspectTest extends AbstractAspectJPolicyEnforcementTest {
@Test
public void testBadPackageName() throws Exception {
assertThat(sourceFile(BadJavaClass.class),
producesCompilationErrorWith(findAspect("ForbiddenPackageNameAspect")));
}
@Test
public void testGoodPackageName() throws Exception {
assertThat(sourceFile(ForbiddenPackageNameAspectTest.class),
compilesWithoutWarningWith(findAspect("ForbiddenPackageNameAspect")));
}
}
当然,在下一步中,我可以扩展它以允许检查特定的错误消息,但是一开始就可以这样做。
答案 1 :(得分:1)