如何用ArchUnit测试限制Singleton注解类及其父类的方法返回值?
解决方案
要让ArchUnit测试覆盖被@Singleton注解类所有可访问的方法(包括继承自父类、实现的接口中的方法,等效于反射getMethods()的效果),可以使用areAccessibleVia断言指定目标类范围:
import com.tngtech.archunit.core.domain.JavaClass; import com.tngtech.archunit.lang.ArchRule; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; import static com.tngtech.archunit.core.domain.JavaClass.Predicates.annotatedWith; ArchRule singletonMethodsMustNotReturnDate = methods() .that().areAccessibleVia(classes().that().areAnnotatedWith(Singleton.class)) // 可选:排除Object类自带的方法,避免无意义的检查 .and().areNotDeclaredIn(Object.class) .should().notHaveRawReturnType(Date.class);
原有测试失效原因
原有代码用areDeclaredInClassesThat().areAnnotatedWith(Singleton.class),仅会检查直接在被@Singleton注解类中声明的方法。示例中Demo接口的print()方法是在接口内定义的,哪怕被Test类实现,只要Test没重写该方法,原有测试就不会扫描到这个继承来的方法。
效果验证
针对你的示例场景:
- 若
Test类未重写print()方法,会继承接口的默认方法(返回Date),新测试会检测到这个违规。 - 示例中
Test重写了print()方法(返回void),不会触发违规,符合预期。 AnotherClass未被@Singleton注解,其实现的Demo方法不会被检测,符合规则要求。
内容的提问来源于stack exchange,提问作者Codinggeek
相关产品推荐
相关产品推荐

