Skip to content

Commit

Permalink
Add an architecture test that checks exception raising.
Browse files Browse the repository at this point in the history
When a new exception is raised then the no-arg constructor
of the exception must never be called. Otherwise the context
of the failure is missing.
  • Loading branch information
uhafner committed Apr 7, 2021
1 parent ddcb4b0 commit e4e62da
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/test/java/edu/hm/hafner/util/ArchitectureRules.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import org.junit.jupiter.params.ParameterizedTest;

import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.AccessTarget.ConstructorCallTarget;
import com.tngtech.archunit.core.domain.JavaCall;
import com.tngtech.archunit.core.domain.JavaConstructorCall;
import com.tngtech.archunit.core.domain.JavaModifier;
import com.tngtech.archunit.core.domain.properties.CanBeAnnotated;
import com.tngtech.archunit.junit.ArchTest;
Expand All @@ -27,6 +29,10 @@ private ArchitectureRules() {
// prevents instantiation
}

/** Never create exception without any context. */
public static final ArchRule NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR =
noClasses().should().callConstructorWhere(new ExceptionHasNoContext());

/** Junit 5 test classes should not be public. */
public static final ArchRule NO_PUBLIC_TEST_CLASSES =
noClasses().that().haveSimpleNameEndingWith("Test")
Expand Down Expand Up @@ -124,4 +130,19 @@ public boolean apply(final JavaCall<?> input) {
&& !"assertTimeoutPreemptively".equals(input.getName());
}
}

private static class ExceptionHasNoContext extends DescribedPredicate<JavaConstructorCall> {
ExceptionHasNoContext() {
super("exception context is missing");
}

@Override
public boolean apply(final JavaConstructorCall javaConstructorCall) {
ConstructorCallTarget target = javaConstructorCall.getTarget();
if (target.getRawParameterTypes().size() > 0) {
return false;
}
return target.getOwner().isAssignableTo(Throwable.class);
}
}
}
3 changes: 3 additions & 0 deletions src/test/java/edu/hm/hafner/util/ArchitectureTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,7 @@ class ArchitectureTest {

@ArchTest
static final ArchRule NO_FORBIDDEN_ANNOTATION_USED = ArchitectureRules.NO_FORBIDDEN_ANNOTATION_USED;

@ArchTest
static final ArchRule NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR = ArchitectureRules.NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR;
}

0 comments on commit e4e62da

Please sign in to comment.