如何使用 ArchUnit 检查构造函数是否在正确的 类 中被调用?
How to check that a constructor is called in the right classes with ArchUnit?
有没有办法用 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
不存在,我没有找到任何可以让我实施这样的测试的东西。
每当您在预定义的流畅 API 中遗漏某些内容时,请尝试定义自定义 predicate/condition。
在您的情况下:这对您有用吗?
@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()));
}
}
}
});
有没有办法用 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
不存在,我没有找到任何可以让我实施这样的测试的东西。
每当您在预定义的流畅 API 中遗漏某些内容时,请尝试定义自定义 predicate/condition。 在您的情况下:这对您有用吗?
@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()));
}
}
}
});