ArchUnit practice: Enforce visibility of methods called only from the same package to package private or private

//Execution environment
* AdoptOpenJDK 11.0.9.1+1
* JUnit 5.7.0
* ArchUnit 0.14.1

Architectural test motivation

Application to the method of Day 15 ArchUnit Practice: Enforce visibility of classes that depend only from the same package to package private.

Architecture test implementation

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.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 that are called only from the same package package private or private() {
        methods()
            .that()
            .arePublic()
            .and(new DescribedPredicate<>("are only called from classes that reside in same package") {
                @Override
                public boolean apply(final JavaMethod method) {
                    return method.getAccessesToSelf()
                        .stream()
                        .map(JavaAccess::getOriginOwner)
                        .allMatch(callerClass
                            -> callerClass.getPackageName().equals(method.getOwner().getPackageName()));
                }
            })
            .should()
            .notBePublic()
            .check(CLASSES);
    }
}

Recommended Posts

ArchUnit practice: Enforce visibility of methods called only from the same package to package private or private
ArchUnit Practice: Enforce visibility of limited-use methods into package private or private
ArchUnit practice: Enforce package private visibility of classes that depend only on the same package
ArchUnit practice: Privately enforce visibility of methods called only from your class
If you want to satisfy the test coverage of private methods in JUnit