我想在我的J2EE项目中编写一个archunit规则来测试当一个类被@Startup注释时,那么它必须包含一个被@PostConstruct注释的方法。
我试过这个
@ArchTest
private val startUpBeansShouldHavePostConstruct: ArchRule = classes().that()
.areAnnotatedWith(Startup::class.java)
.shouldHave(methods().that().areAnnotatedWith(PostConstruct::class.java))
.because("classes with @Startup should contain a @PostConstruct annotated method")
但是这不会在 shouldHave() 行中编译。我有点困惑如何定义这样的规则。我的实际目标是制定一条规则,规定应该有“恰好一个”带注释的方法。
import com.tngtech.archunit.base.DescribedPredicate.describe
import com.tngtech.archunit.core.domain.JavaClass
import com.tngtech.archunit.junit.ArchTest
import com.tngtech.archunit.lang.conditions.ArchConditions.have
import com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes
你可以使用
@ArchTest
private val startUpBeansShouldHavePostConstruct =
classes()
.that().areAnnotatedWith(Startup::class.java)
.should(have(aMethodAnnoatedWith(PostConstruct::class.java)))
private fun aMethodAnnoatedWith(annotationClass: Class<out Annotation>) =
describe("a method annotated @${annotationClass.simpleName}") {
javaClass: JavaClass ->
javaClass.methods.count { it.isAnnotatedWith(PostConstruct::class.java) } == 1 }
}