测试的标注类只有一个公共方法。

huangapple go评论95阅读模式
英文:

Test annotated class only has one public method

问题

最佳方法编写ArchUnit测试,测试带有特定注解(例如Spring Framework的@Component注解)的类仅具有一个公共方法是什么?

我还没有尝试过任何方法,因为我仍在学习ArchUnit。

英文:

What is the best way to write an ArchUnit test that tests that classes that are annotated with a specific annotation, e.g. the Spring Framework @Component annotation, only have one public method?

I haven't tried anything yet because I am still learning ArchUnit.

答案1

得分: 1

Here is the translation of the code portion you provided:

每当预定义的流畅 API (`classes().that()..should().…`) 无法提供解决方案时您可以定义自定义的 `DescribedPredicate`s 和 `ArchConditions`s并使用 `classes().that().should()`。

对于您的问题我会使用以下内容

```java
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.base.DescribedPredicate.describe;
import static com.tngtech.archunit.core.domain.JavaModifier.PUBLIC;
import static com.tngtech.archunit.core.domain.properties.HasModifiers.Predicates.modifier;
import static com.tngtech.archunit.lang.conditions.ArchConditions.have;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;

public class StackOverflow76272127 {

  @ArchTest
  ArchRule components_should_have_only_one_public_method =
      classes()
          .that().areAnnotatedWith(Component.class)
          .should(have(describe("only one public method", javaClass ->
              javaClass.getMethods().stream().filter(modifier(PUBLIC)).count() == 1
          )));
}  

Please note that I've translated the code while preserving its formatting and structure.

<details>
<summary>英文:</summary>

Whenever the predefined fluent API (`classes().that().….should().…`) does not offer a solution, you can define custom `DescribedPredicate`s and `ArchConditions`s and use `classes().that(…).should(…)`.

For your issue, I would use this:

```java
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.base.DescribedPredicate.describe;
import static com.tngtech.archunit.core.domain.JavaModifier.PUBLIC;
import static com.tngtech.archunit.core.domain.properties.HasModifiers.Predicates.modifier;
import static com.tngtech.archunit.lang.conditions.ArchConditions.have;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;

public class StackOverflow76272127 {

  @ArchTest
  ArchRule components_should_have_only_one_public_method =
      classes()
          .that().areAnnotatedWith(Component.class)
          .should(have(describe(&quot;only one public method&quot;, javaClass -&gt;
              javaClass.getMethods().stream().filter(modifier(PUBLIC)).count() == 1
          )));
}  

huangapple
  • 本文由 发表于 2023年5月17日 20:30:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定