//Execution environment
* AdoptOpenJDK 11.0.9.1+1
* JUnit 5.7.0
* ArchUnit 0.14.1
Day 16 ArchUnit Practice: Enforce visibility of methods called only from the same package into package private or private application.
package com.example;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaAccess;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.domain.JavaMethod;
import com.tngtech.archunit.core.domain.JavaModifier;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption;
import org.junit.jupiter.api.Test;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods;
class ArchitectureTest {
//Class to be inspected
private static final JavaClasses CLASSES =
new ClassFileImporter()
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
.importPackages("com.example");
@Test
void Make methods called only from your class private() {
methods()
.that(new DescribedPredicate<>("are public or are package private") {
@Override
public boolean apply(final JavaMethod method) {
return ! method.getModifiers().contains(JavaModifier.PRIVATE)
&& ! method.getModifiers().contains(JavaModifier.PROTECTED);
}
})
.and(new DescribedPredicate<>("that are only called in declared class") {
@Override
public boolean apply(final JavaMethod method) {
return method.getAccessesToSelf()
.stream()
.map(JavaAccess::getOriginOwner)
.allMatch(callerClass
-> callerClass.getFullName().equals(method.getOwner().getFullName()));
}
})
.should()
.bePrivate()
.check(CLASSES);
}
}
Recommended Posts