Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore classes in test class with ArchUnit

Tags:

I wrote my first ArchUnit test:

import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.*; // more non-static imports  @RunWith(ArchUnitRunner.class) @AnalyzeClasses(packages = "my.domain.project") public class PackageStructureTests {      @ArchTest public static final ArchRule NO_CYCLES = slices().matching("my.domain.project.(**)")             .namingSlices("package:$1").should().beFreeOfCycles();  } 

The problem is that it also analyzes classes in tests, which don't follow that simple dependency constraint.

How do I limit the test to the "production" classes?

The project gets built with Maven, so the classes are in separate directories.

It is not sufficient to separate classes with names ending in "Tests" or something because there are many classes that aren't tests, but are only present on the test classpath.

like image 787
Jens Schauder Avatar asked Jun 20 '17 13:06

Jens Schauder


1 Answers

It seems that the API is not guiding very well with respect to this, because you're not the first one wondering about this (this was also issue #1 on Github https://github.com/TNG/ArchUnit/issues/1).

To answer the question though, the Annotation @AnalyzeClasses has an extra attribute importOptiosn (since ArchUnit 0.5.0 an array ANDing all options), which takes arbitrary implementations of ImportOption, where you can specify which Location (basically the URI) to include.

Since excluding tests is rather common, this ImportOption is already predefined (for Maven and Gradle), so you can write

@AnalyzeClasses(..., importOptions = { ImportOption.DoNotIncludeTests.class }) public class MyTest { … } 

I don't think there is a generic solution for all setups (thus the freedom to just write your own ImportOption to decide which locations to include). However, for standard Maven and Gradle setups, it should be working.

like image 68
pete83 Avatar answered Sep 17 '22 14:09

pete83