【问题标题】:How to check that a constructor is called in the right classes with ArchUnit?如何使用 ArchUnit 检查是否在正确的类中调用了构造函数?
【发布时间】:2021-10-26 12:56:52
【问题描述】:

有什么办法可以用 ArchUnit 来执行这样的规则:

@ArchTest
    static final ArchRule events_must_be_created_by_aggregates =
            noConstructors().that().areDeclaredInClassesThat().areAssignableTo(Event.class).should().beCalledInClassesThat().areNotAssignableFrom(Aggregate.class)
                    .because("the aggregate should manage its own lifecycle and events");

这里的问题是 beCalledInClassesThat 不存在,我找不到任何可以让我实现这样的测试的东西。

【问题讨论】:

    标签: java archunit


    【解决方案1】:

    每当您错过预定义的 fluent API 中的某些内容时,请尝试定义自定义谓词/条件。 就你而言:这对你有用吗?

    @ArchTest
    static final ArchRule events_must_be_created_by_aggregates = constructors()
        .that().areDeclaredInClassesThat().areAssignableTo(Event.class)
        .should(new ArchCondition<JavaConstructor>("be called from aggregates") {
            @Override
            public void check(JavaConstructor constructor, ConditionEvents events) {
                for (JavaConstructorCall call : constructor.getCallsOfSelf()) {
                    if (!call.getOriginOwner().isAssignableTo(Aggregate.class)) {
                        events.add(SimpleConditionEvent.violated(call, call.getDescription()));
                    }
                }
            }
        });
    

    【讨论】:

    猜你喜欢
    • 2013-01-11
    • 2019-05-14
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2021-11-12
    相关资源
    最近更新 更多