Search code examples
archunit

Is there a similar option to ImportOption.DoNotIncludeTests on a per test level in ArchUnit


My question is if we can filter out classes from the test packages programmatically on a per test basis in ArchUnit ?

It should be basically the same behaviour that @AnalyzeClasses(packages = "....", importOptions = ImportOption.DoNotIncludeTests.class) does on a class level.

Background is that we have some ArchTests that should run against all classes but also some which only should run against classes that are not in the test location.

Something like that maybe?

    Architectures.onionArchitecture()
            ....
            .check(classes.that(areNotTests())); ??

(We can achieve the goal by creating two Classes that hold the ArchUnit tests seperately and only add the ImportOption.DoNotIncludeTests to the one of them. But we would rather have one set of classes to analyze and decide on a per test level. If there is a way to achieve that)


Solution

  • ImportOptions operate on Locations, but you can try to use the following adapter:

    DescribedPredicate<JavaClass> notTests = DescribedPredicate.describe("not tests",
        javaClass -> javaClass.getSource()
                .map(Source::getUri)
                .map(Location::of)
                .map(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS::includes)
                .orElse(true)  // test classes should have a source;
             //  alternatively, you could probably also use:
             // .orElseThrow(IllegalStateException::new)
    );