ArchUnit:测试一个类是否包含带注释的方法

问题描述 投票:0回答:1

我想在我的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() 行中编译。我有点困惑如何定义这样的规则。我的实际目标是制定一条规则,规定应该有“恰好一个”带注释的方法。

kotlin testing archunit
1个回答
0
投票

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 } }

© www.soinside.com 2019 - 2024. All rights reserved.