英文:
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("only one public method", javaClass ->
javaClass.getMethods().stream().filter(modifier(PUBLIC)).count() == 1
)));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论