我正在尝试使用ArchUnit进行单元测试,以检查是否有未使用的类。但是我不知道如何检查MyClass.class是否引用了某些类。
例如,我有一个课程:
public class MyClass {
...
}
然后我通过某种方法引用此类:
public class MySecondClass{
public void methodA(){
methodThatTakesClassAsParameter(MyClass.class);
}
...
}
如何从ArchUnit中看到MySecondClass引用了MyClass?
答案 0 :(得分:1)
我可能会为您提供(部分)解决方案。
创建一个ArchCondition
public static class NotBeUnreferenced extends ArchCondition<JavaClass> {
NotBeUnreferenced() {
super("is not referenced by any other compilation units");
}
@Override
public void check(JavaClass javaClass, ConditionEvents events) {
Set<JavaAccess<?>> accessesFromOtherCompilationUnits = new HashSet<JavaAccess<?>>();
accessesFromOtherCompilationUnits.addAll(javaClass.getAccessesToSelf());
accessesFromOtherCompilationUnits.removeAll(javaClass.getAccessesFromSelf());
if (accessesFromOtherCompilationUnits.isEmpty() && javaClass.getDirectDependenciesToSelf().isEmpty()) {
String message = createCheckMessage(javaClass, "is unreferenced");
events.add(new SimpleConditionEvent(javaClass, false, message));
}
}
// taken from com.tngtech.archunit.lang.conditions.ArchConditions
public static <T extends HasDescription & HasSourceCodeLocation> String createCheckMessage(T object,
String message) {
return object.getDescription() + " " + message + " in " + object.getSourceCodeLocation();
}
}
使用ArchCondition
ArchCondition<JavaClass> notBeUnreferenced = new NotBeUnreferenced();
ArchRule rule = classes().should(notBeUnreferenced);
collectedRules.add(rule);
您可能想要
@EJB
)排除带有某些批注的类(例如@Dependent
,@Stateless
,rule = rule.or(ArchConditions.beAnnotatedWith(...))
)已知限制
请注意,如果唯一的访问权限是编译单元(类,接口,枚举),则认为未引用
.class
的访问和其他反射访问