Skip to content

onlyHaveDependentClassesThat() vs onlyBeAccessed() #302

@rudolfgrauberger

Description

@rudolfgrauberger

My folder/package structure

com.example.post
|- api
    PostApi.java
|- service
    PostService.java
public class PostApi {
}
@Service
public class PostService {
    @Autowired
    private PostApi postApi;
}

My first try

@AnalyzeClasses(packages = "com.example.post", importOptions = { ImportOption.DoNotIncludeTests.class, ImportOption.DoNotIncludeJars.class, ImportOption.DoNotIncludeArchives.class })
public class MyTest {
    @ArchTest
    public static final ArchRule apiClassesShouldOnlyBeAccessedByApis = classes()
        .that().resideInAPackage("..api..")
        .should().onlyBeAccessed().byAnyPackage("..api..");
}

Test passed! (undesired and not expected)

I changed the test to

@AnalyzeClasses(packages = "com.example.post", importOptions = { ImportOption.DoNotIncludeTests.class, ImportOption.DoNotIncludeJars.class, ImportOption.DoNotIncludeArchives.class })
public class MyTest {
    @ArchTest
    public static final ArchRule apiClassesShouldOnlyBeAccessedByApis = classes()
            .that().resideInAPackage("..api..")
            .should().onlyBeAccessed().byClassesThat().resideInAnyPackage("..api..");
}

Test passed! (undesired and not expected)

If I change the Test to

@AnalyzeClasses(packages = "com.example.post", importOptions = { ImportOption.DoNotIncludeTests.class, ImportOption.DoNotIncludeJars.class, ImportOption.DoNotIncludeArchives.class })
public class MyTest {
    @ArchTest
    public static final ArchRule apiClassesShouldOnlyBeAccessedByApis = classes()
        .that().resideInAPackage("..api..")
        .should().onlyHaveDependentClassesThat().resideInAnyPackage("..api..");
}

Test failed with message (as expected and desired):

java.lang.AssertionError: Architecture Violation [Priority: MEDIUM] - Rule 'classes that reside in a package '..api..' should only have dependent classes that reside in any package ['..api..']' was violated (1 times):
Field <com.example.post.service.PostService.tagApi> has type <com.example.post.api.PostApi> in (PostService.java:0)

Why the different results? I don't think I understand the difference between onlyHaveDependentClassesThat() and onlyBeAccessed()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions