Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude a class in an ArchUnit rule?

While creating a rule for a layered architecture in ArchUnit, it's not clear to me how to exclude a single class (Main). The base example excludes with a source and a target.

... but I don't get how it converts to my need. I just want just Main to be ignored. Why? Because Main references all layers since it injects all dependencies in place.

The original code is in my GitHub along with the failing test. (the project is a dummy one so it's straightforward to run; just clone it, run the tests and see one failing).

like image 897
Luís Soares Avatar asked Jan 10 '20 08:01

Luís Soares


2 Answers

Consider you have imported all your classes:

JavaClasses classes = new ClassFileImporter().importPackages("org.example");

Then you typically check all these classes against an ArchRule, no matter if it's a class rule or an architecture rule:

ArchRule rule = classes()
    .that().areAnnotatedWith(Service.class)
    .should().haveSimpleNameEndingWith("Service");

rule.check(classes);

To exclude classes from the rule, you could filter classes and pass the filtered JavaClasses to the rule:

import static com.tngtech.archunit.base.DescribedPredicate.not;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.equivalentTo;
import static com.tngtech.archunit.lang.conditions.ArchPredicates.are;

JavaClasses allExceptMain = classes.that(are(not(equivalentTo(Main.class))));
rule.check(allExceptMain);

To exclude the class Main and all classes that are defined inside of Main (inner classes, anonymous classes, lambdas etc.) you could adjust the filter:

import static com.tngtech.archunit.base.DescribedPredicate.not;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf;

JavaClasses allExceptMain = classes.that(not(belongToAnyOf(Main.class)));
rule.check(allExceptMain);
like image 78
Roland Weisleder Avatar answered Nov 20 '22 00:11

Roland Weisleder


How about something like this:

.ignoreDependency(fullNameMatching("users.WebAppConfig"), alwaysTrue())
like image 20
sylvain decout Avatar answered Nov 19 '22 23:11

sylvain decout