# Add ArchUnit Architecture Tests to a Maven Spring Boot Project

Yes. An agent reads your packages and their imports, writes ArchUnit rules that fail when a slice reaches into another, runs them with Maven and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-architecture-tests/maven/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the package graph before it writes a rule, because a rule copied from a blog post fails on the first build for reasons that have nothing to do with the architecture. In a project like spring-projects/spring-petclinic, `pom.xml` inherits `spring-boot-starter-parent` 4.1.0 with `java.version` 17, depends on the split starters `spring-boot-starter-webmvc`, `spring-boot-starter-data-jpa`, `spring-boot-starter-thymeleaf`, `spring-boot-starter-validation`, `spring-boot-starter-cache` and `spring-boot-starter-actuator`, and for tests on `spring-boot-starter-webmvc-test`, `spring-boot-starter-data-jpa-test`, `spring-boot-testcontainers` and `testcontainers-mysql`. The build already runs `spring-javaformat-maven-plugin` at `validate`, a nohttp Checkstyle check, JaCoCo and the CycloneDX plugin, and `.github/workflows/maven-build.yml` runs `./mvnw -B verify` on Java 17. The code under `org.springframework.samples.petclinic` is four packages: `model` with the `@MappedSuperclass` types `BaseEntity`, `NamedEntity` and `Person`; `owner` with `Owner`, `Pet`, `PetType`, `Visit`, three `@Controller`s, `OwnerRepository` and `PetTypeRepository` extending `JpaRepository`, a `PetValidator` and a `PetTypeFormatter`; `vet` with `Vet`, `Specialty`, `Vets`, `VetController` and a `VetRepository` extending `Repository`; and `system` with `CacheConfiguration`, `WebConfiguration`, `WelcomeController` and `CrashController`. Each package has a `package-info.java`.

Reading the imports gives the rules their shape. `owner` imports only `model`, `vet` imports only `model`, `system` imports nothing from its siblings, and the root package's `PetClinicRuntimeHints` imports `model` and `vet`. So the intended structure is three slices, `owner`, `vet` and `system`, that depend on `model` and never on each other, and a root package that may see all of them. The tests tell the same story with one exception: `src/test/java/.../service/ClinicServiceTests` imports `owner` and `vet` together, which is a test of both slices and must be excluded from the slice rule or the rule fails on day one. The agent writes `ArchitectureTests` in `src/test/java/org/springframework/samples/petclinic/` with ArchUnit: `slices().matching("..petclinic.(*)..")` restricted to `owner`, `vet` and `system` with `should().notDependOnEachOther()`; `classes().that().resideInAPackage("..model..").should().onlyDependOnClassesThat().resideInAnyPackage("..model..", "java..", "jakarta..", "org.springframework..")`; `classes().that().areAnnotatedWith(Controller.class).should().resideInAnyPackage("..owner..", "..vet..", "..system..")`; and `noClasses().that().resideInAPackage("..model..").should().dependOnClassesThat().resideInAPackage("org.springframework.web..")`, so an entity can never grow a web import. Each rule gets a one-line `because` so the failure message says what the team meant.

The dependency choice follows the test engine the parent manages. Spring Boot 4 moved its test starters to the JUnit line that ArchUnit publishes a matching artifact for, and ArchUnit ships both `archunit-junit5` and `archunit-junit6`, so the agent reads the managed `junit-jupiter` version from `./mvnw help:effective-pom` and picks the artifact that matches, in `test` scope, with the version written in `pom.xml`'s properties block beside `checkstyle.version` and `jacoco.version` as the file already does. With that engine the class is annotated `@AnalyzeClasses(packages = "org.springframework.samples.petclinic", importOptions = ImportOption.DoNotIncludeTests.class)`, each rule is a `@ArchTest` field, and the whole class runs under Surefire like the other tests. The agent runs `./mvnw spring-javaformat:apply` on the new file first, because the `validate` phase fails the build on an unformatted class, and it runs the nohttp Checkstyle check because the `because` strings must not contain an `http://` link.

Then it proves the rules bite. In its own sandbox it runs `./mvnw -B verify`, which runs the new class with the rest of the suite, and keeps the Surefire report. It then adds a temporary `import org.springframework.samples.petclinic.owner.Owner;` to `VetController`, runs the test class alone with `./mvnw -Dtest=ArchitectureTests test`, and reads the failure, which names `VetController`, `Owner` and the slice rule; the import is removed before the commit and both outputs go into the pull request. It runs the Gradle build's twin too, `./gradlew test --tests ArchitectureTests`, after adding the same dependency to `build.gradle`'s `testImplementation` list, because the repository builds with both tools and a rule that only one build runs is a rule half the pull requests skip.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add ArchUnit architecture tests to this Maven Spring Boot project. Read pom.xml, build.gradle, every package-info.java, every import between the packages under src/main/java and src/test/java, and the GitHub workflows first. Write down the package slices the imports show and which test classes cross them. Read the managed JUnit Jupiter version from the effective POM and pick the matching ArchUnit JUnit artifact in test scope, with its version in the properties block, and add the same dependency to build.gradle. Write one test class with AnalyzeClasses excluding tests and rules for: slices that must not depend on each other, the model package depending only on itself and framework packages, controllers living only in the slices, and model classes never importing Spring web. Give each rule a because clause. Run the Spring Java Format apply and the nohttp check, run ./mvnw -B verify and ./gradlew test --tests ArchitectureTests, then prove one rule fails by adding a cross-slice import temporarily, record the failure message, remove the import, and open a pull request with both outputs.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that adds `src/test/java/org/springframework/samples/petclinic/ArchitectureTests.java` and one `test`-scope dependency to `pom.xml` and `build.gradle`, with nothing changed under `src/main/java`. The description lists the slices and the imports that justify each rule, quotes the Surefire summary from `./mvnw -B verify` and the Gradle run, and quotes the failure message from the deliberate cross-slice import, so a reviewer sees what a violation will look like in CI before one happens.

The repository's `Java CI with Maven` and Gradle workflows run on the pull request and execute the new class with the rest of the suite, so the checks on the pull request are the first real run of the rules. A reviewer decides whether the `service` test package, which the rules leave out, should move into the slices it tests, and whether to add Spring Modulith's `ApplicationModules.verify()` as a second opinion; the pull request describes both and does neither.

## Run it on every pull request that adds an import

Once merged, the tests do the ongoing work: every pull request runs them through `maven-build.yml`, and an `@Controller` in `vet` that starts using an `owner` repository fails `./mvnw -B verify` with the class names in the log. In the console, an automation in the Project with the repository, with a `github` trigger on `check_suite.failure` and the prompt "if the failing test is ArchitectureTests, explain which rule failed and which import caused it in a comment, and say whether the rule or the code should change", turns a red check into a sentence the author can act on. The trigger adds the event after the prompt and fires only for work by owners, members and collaborators.

For a second project on the same layout, send this body again with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started; the run reads that project's own imports, so a project with a `service` layer gets a layered rule instead of slices.

## Why run it on Rush?

Architecture rules are only worth having when they match the code that exists, and the only way to know is to read every import and run the rules against the real build. The agent does both in its own sandbox: it maps the packages, writes rules that pass today, picks the ArchUnit artifact that matches the JUnit line the Boot parent manages, formats the class the way the `validate` phase demands, and then breaks a rule on purpose so the pull request shows the message the next violator will read.

A rule written on a laptop tends to skip the Gradle build or the formatter and fails the first CI run for the wrong reason. Here both builds run in the sandbox, the record keeps every command, and the pull request quotes them, so a reviewer argues about the architecture rather than about whether the test compiles.

## Frequently asked questions

### Will the new tests fail on the current code?

No. The rules are written from the imports that exist, and the agent runs the whole suite with `./mvnw -B verify` before opening the pull request. The one test class that imports two slices at once is excluded through `DoNotIncludeTests`, and the pull request names it so the team can decide whether to move it.

### Why ArchUnit rather than Spring Modulith?

ArchUnit lets the rules say exactly what the imports show, including a rule about `model` never touching Spring web, and it works on any package layout. Spring Modulith's `ApplicationModules.verify()` infers modules from the packages under the application class and would treat `owner`, `vet`, `system` and `model` as four modules with `model` needing to be opened; the pull request explains it as a follow-up rather than mixing the two.

### Which ArchUnit artifact does it add?

The one that matches the JUnit Jupiter line the Spring Boot parent manages, read from the effective POM rather than guessed, since ArchUnit publishes separate JUnit 5 and JUnit 6 integrations. The version goes in the `properties` block beside the other pinned tools, and the same coordinates go into `build.gradle`.

### How much does it slow down the build?

The class imports the compiled classes once and evaluates a handful of rules against them, which is small beside the Testcontainers-backed integration tests the suite already runs. The pull request quotes the Surefire timing for the class so the number is read, not estimated.

## More Maven jobs

- [Add Checkstyle to a Maven Build](https://getrush.ai/run/add-checkstyle/maven/)
- [Add CodeQL Scanning to a Maven Spring Boot Project](https://getrush.ai/run/add-codeql-scanning/maven/)
- [Add Coverage Reporting to CI for a Maven Spring Boot Project](https://getrush.ai/run/add-coverage-to-ci/maven/)

## The same job on other stacks

- [Add Architecture Tests to a .NET Clean Architecture Solution](https://getrush.ai/run/add-architecture-tests/dotnet/)

## More jobs like this: Write the missing tests

- [Add Benchmarks That Catch Performance Regressions in a Python Library](https://getrush.ai/run/add-benchmarks-to-ci/python/)
- [Add chart-testing and a kind Install Test to a Helm Chart's CI](https://getrush.ai/run/add-chart-testing/helm/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
