Jakub Ch.
Jakub Ch.

Reputation: 3717

ArchUnit ensuring annotation presence

Given ArchUnit library in version 0.12:

Is it possible to test a scenario "methods annotated with A should also be annotated with B or be declared in a type annotated with B"?

Example:

A.java

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
}

B.java

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface B {
}

TestCases.java

public class TestCases {

    static class ShouldFail {

        @A
        public void m() {
        }
    }

    static class ShouldPass {

        @A
        @B
        public void m() {
        }
    }

    @B
    static class ShouldPassToo {

        @A
        public void m() {
        }
    }
}

What have I tried?

I've thought that ArchConditions.beDeclaredInClassesThat would do the job so I've prepared following rule:

MethodsShouldConjunction rule = methods()
    .that()
    .areAnnotatedWith(A.class)
    .should()
    .beAnnotatedWith(B.class)
    .orShould(beDeclaredInClassesThat(areAnnotatedWith(B.class))); //<-- doesn't compile

...but apparently I've misunderstood the purpose of mentioned method. Javadoc of that utility wasn't helpful at all. Can I replace the last line with anything working which fulfills the assertion "methods declared in a type annotated with B"?

Upvotes: 0

Views: 1666

Answers (1)

Jakub Ch.
Jakub Ch.

Reputation: 3717

Turned out I've needlessly tried to pass parameter to orShould method. To achieve my goal the rule should be extended using parameterless methods:

methods()
    .that()
    .areAnnotatedWith(A.class)
    .should()
    .beAnnotatedWith(B.class)
    .orShould()
    .beDeclaredInClassesThat()
    .areAnnotatedWith(B.class);

Upvotes: 3

Related Questions