├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── architecture.puml ├── build.gradle ├── docker-compose.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── company │ │ └── app │ │ ├── adapters │ │ ├── primary │ │ │ └── web │ │ │ │ ├── BookController.java │ │ │ │ ├── BookPojo.java │ │ │ │ ├── JsonConfiguration.java │ │ │ │ └── LegacyBooksApi.java │ │ └── secondary │ │ │ └── mongodb │ │ │ ├── BookDocument.java │ │ │ ├── BooksRepository.java │ │ │ ├── MongoBooksRepository.java │ │ │ └── MongoConfiguration.java │ │ ├── application │ │ ├── BookCatalogApplication.java │ │ └── usecases │ │ │ ├── AddBookUseCase.java │ │ │ └── FindBooksUseCase.java │ │ └── domain │ │ ├── model │ │ ├── Author.java │ │ ├── Book.java │ │ ├── Isbn.java │ │ └── Title.java │ │ └── services │ │ └── BookDomainService.java └── resources │ ├── application.properties │ └── archunit_ignore_patterns.txt └── test ├── http ├── books.addbook.http └── books.getbooks.http └── java └── com └── company └── app ├── application └── BookCatalogApplicationTest.java └── architecture ├── AdaptersLayerComponentsTest.java ├── ApplicationComponentsTest.java ├── ArchitectureTest.java ├── DomainComponentsTest.java ├── GeneralCodingRulesTest.java ├── LayeredArchitectureTest.java ├── PrimaryAdaptersComponentsTest.java ├── SecondaryAdaptersComponentsTest.java ├── SlicesTest.java └── SpringCodingRulesTest.java /.gitattributes: -------------------------------------------------------------------------------- 1 | *.bat text eol=crlf 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | /build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | 6 | ### STS ### 7 | .apt_generated 8 | .classpath 9 | .factorypath 10 | .project 11 | .settings 12 | .springBeans 13 | .sts4-cache 14 | 15 | ### IntelliJ IDEA ### 16 | .idea 17 | *.iws 18 | *.iml 19 | *.ipr 20 | /out/ 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | 29 | ### VS Code ### 30 | .vscode/ 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Jonas Havers 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # archunit-examples 2 | 3 | This repository contains some [ArchUnit](https://archunit.org) tests for a simplified book-catalog Spring Boot application. 4 | 5 | A ports-and-adapters architecture was chosen to demonstrate many of the features of ArchUnit. 6 | 7 | ![PlantUML architecture.puml](http://www.plantuml.com/plantuml/png/dL3DQkCm4BxhAMQJImAnoR8i8Ki8yThu75ZsL7gOIEDKZIKPIIwKjkzU2Tkfsj9BqK4p-dw-6HsSH-jxrJB7iINucVzcp5saxj2Y0gazsGOvmHC3E26_dAtfjIXDQopCctKy4J5Ma1rVV_5mJkmbDU96TKQJzjyp-Y6eaPf06T6tjD2eQ0Nt-837u8HdMYO1Dn6zXTqkpnD6dk_tZ8twevKAxICK0hkme5i1ZbNU3T0IqC5OJooO5vjgKrUJop_YHeilVDm83avJzzbhCYkwhfKSlJGwkBmrKPxsCA_hOhqjsM89i_-EiX8TmT5OFulCtb5yYFqxHWfUCokZK8Ou4UyXQIX3I5bNVxUCVVo2y8sJ3Vo95PjMIpdF-tIGG9IgQqcHzcmIP-bIB5qmIxKf4iF70STinac7I6YCYLSKk0oroAwp59RVIK_SzvROWRJeLViA) 8 | 9 | The [ArchUnit tests](src/test/java/com/company/app/architecture) can be found in the `com.company.app.architecture` package in `src/test/java`. 10 | They can be executed as regular unit tests with `./gradlew test`. No ArchUnit JUnit runner was used in this example. 11 | 12 | If you want to run the application, you can use the `docker-compose.yml` file to start a local docker MongoDB instance. 13 | With `./gradlew bootRun` you execute the application itself. 14 | There are also [HTTP tests](src/test/http/) in `src/test/http` which you can execute with IntelliJ IDEA to test the books API endpoints. 15 | Of course, you can also use cURL. 16 | -------------------------------------------------------------------------------- /architecture.puml: -------------------------------------------------------------------------------- 1 | @startuml 2 | scale 1.5 3 | 4 | skinparam interface { 5 | backgroundColor #f0f0f0 6 | borderColor #3c3c3b 7 | } 8 | 9 | skinparam component { 10 | backgroundColor #f0f0f0 11 | borderColor #3c3c3b 12 | } 13 | 14 | !define module(name, javaPackage) component [name] <<..javaPackage..>> 15 | 16 | module(Primary Adapters, adapters.primary) as primaryAdapters #A7D7FD 17 | module(Secondary Adapters, adapters.secondary) as secondaryAdapters #A7D7FD 18 | 19 | module(Application, application) as application #FFA09C 20 | () "Use-Case Port" as useCasePort 21 | () "Use-Case" as useCase 22 | 23 | module(Domain, domain) as domain #FCFDB9 24 | 25 | primaryAdapters ..> useCase : use 26 | secondaryAdapters ..|> useCasePort : implement 27 | useCase - application 28 | application - useCasePort 29 | application ..> domain : use 30 | 31 | center footer Ports-and-Adapters Architecture 32 | @enduml 33 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.5.RELEASE' 3 | id 'java' 4 | } 5 | 6 | apply plugin: 'io.spring.dependency-management' 7 | 8 | group = 'com.company' 9 | version = '0.0.1-SNAPSHOT' 10 | sourceCompatibility = '1.8' 11 | 12 | repositories { 13 | mavenCentral() 14 | } 15 | 16 | dependencies { 17 | implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive' 18 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 19 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 20 | testImplementation 'io.projectreactor:reactor-test' 21 | testCompile 'com.tngtech.archunit:archunit:0.10.2' 22 | } 23 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | book-catalog-db: 4 | image: mongo:4.1 5 | volumes: 6 | - ${PWD}/mongodb/import-data:/data/db-import 7 | ports: 8 | - 27017:27017 9 | networks: 10 | - book-catalog-net 11 | networks: 12 | book-catalog-net: 13 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JonasHavers/archunit-examples/d60b8cea830d9298cb98d51ad82078002950f9fc/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | } 5 | } 6 | rootProject.name = 'archunit-examples' 7 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/adapters/primary/web/BookController.java: -------------------------------------------------------------------------------- 1 | package com.company.app.adapters.primary.web; 2 | 3 | import com.company.app.application.usecases.AddBookUseCase; 4 | import com.company.app.application.usecases.FindBooksUseCase; 5 | import org.springframework.web.bind.annotation.*; 6 | import reactor.core.publisher.Flux; 7 | import reactor.core.publisher.Mono; 8 | 9 | @RestController 10 | @RequestMapping("/books") 11 | class BookController { 12 | private final FindBooksUseCase findBooksUseCase; 13 | private final AddBookUseCase addBookUseCase; 14 | 15 | public BookController(FindBooksUseCase findBooksUseCase, AddBookUseCase addBookUseCase) { 16 | this.findBooksUseCase = findBooksUseCase; 17 | this.addBookUseCase = addBookUseCase; 18 | } 19 | 20 | @GetMapping("/") 21 | public Flux bookList() { 22 | FindBooksUseCase.Request request = new FindBooksUseCase.Request(); 23 | FindBooksUseCase.Response response = findBooksUseCase.invoke(request); 24 | return response.books; 25 | } 26 | 27 | @PostMapping("/") 28 | public Mono addBook(@RequestBody AddBookUseCase.BookDto bookDto) { 29 | AddBookUseCase.Request request = new AddBookUseCase.Request(bookDto); 30 | AddBookUseCase.Response response = addBookUseCase.invoke(request); 31 | return response.addBook.thenReturn(bookDto); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/adapters/primary/web/BookPojo.java: -------------------------------------------------------------------------------- 1 | package com.company.app.adapters.primary.web; 2 | 3 | public class BookPojo { 4 | public String isbn; 5 | public String title; 6 | public String author; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/adapters/primary/web/JsonConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.company.app.adapters.primary.web; 2 | 3 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 | import com.fasterxml.jackson.annotation.PropertyAccessor; 5 | import com.fasterxml.jackson.databind.DeserializationFeature; 6 | import com.fasterxml.jackson.databind.ObjectMapper; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.context.annotation.Primary; 10 | 11 | @Configuration 12 | class JsonConfiguration { 13 | 14 | @Primary 15 | @Bean 16 | public ObjectMapper objectMapper() { 17 | ObjectMapper objectMapper = new ObjectMapper(); 18 | objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); 19 | objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 20 | return objectMapper; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/adapters/primary/web/LegacyBooksApi.java: -------------------------------------------------------------------------------- 1 | package com.company.app.adapters.primary.web; 2 | 3 | import com.company.app.adapters.secondary.mongodb.BookDocument; 4 | import com.company.app.adapters.secondary.mongodb.MongoBooksRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.ResponseBody; 9 | import reactor.core.publisher.Flux; 10 | 11 | @Controller 12 | @RequestMapping("/api/books") 13 | public class LegacyBooksApi { 14 | @Autowired 15 | private MongoBooksRepository mongoBooksRepository; 16 | 17 | @RequestMapping("/") 18 | @ResponseBody 19 | public Flux findAll() { 20 | return mongoBooksRepository.findAll(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/adapters/secondary/mongodb/BookDocument.java: -------------------------------------------------------------------------------- 1 | package com.company.app.adapters.secondary.mongodb; 2 | 3 | import org.springframework.data.mongodb.core.mapping.Document; 4 | 5 | import java.util.Objects; 6 | 7 | @Document 8 | public class BookDocument { 9 | public String isbn; 10 | public String title; 11 | public String author; 12 | 13 | @Override 14 | public boolean equals(Object o) { 15 | if (this == o) return true; 16 | if (o == null || getClass() != o.getClass()) return false; 17 | BookDocument that = (BookDocument) o; 18 | return Objects.equals(isbn, that.isbn) && 19 | Objects.equals(title, that.title) && 20 | Objects.equals(author, that.author); 21 | } 22 | 23 | @Override 24 | public int hashCode() { 25 | return Objects.hash(isbn, title, author); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/adapters/secondary/mongodb/BooksRepository.java: -------------------------------------------------------------------------------- 1 | package com.company.app.adapters.secondary.mongodb; 2 | 3 | import com.company.app.application.usecases.AddBookUseCase; 4 | import com.company.app.application.usecases.FindBooksUseCase; 5 | import org.springframework.stereotype.Repository; 6 | import reactor.core.publisher.Flux; 7 | import reactor.core.publisher.Mono; 8 | 9 | @Repository 10 | public class BooksRepository implements FindBooksUseCase.FindBooksPort, AddBookUseCase.AddBookPort { 11 | private final MongoBooksRepository delegateRepository; 12 | 13 | public BooksRepository(MongoBooksRepository delegateRepository) { 14 | this.delegateRepository = delegateRepository; 15 | } 16 | 17 | @Override 18 | public Flux findAllBooks() { 19 | return delegateRepository 20 | .findAll() 21 | .map(bookDocument -> { 22 | FindBooksUseCase.BookDto bookDto = new FindBooksUseCase.BookDto(); 23 | bookDto.isbn = bookDocument.isbn; 24 | bookDto.title = bookDocument.title; 25 | bookDto.author = bookDocument.author; 26 | return bookDto; 27 | }); 28 | } 29 | 30 | @Override 31 | public Mono addBook(AddBookUseCase.BookDto bookDto) { 32 | BookDocument bookDocument = new BookDocument(); 33 | bookDocument.isbn = bookDto.isbn; 34 | bookDocument.title = bookDto.title; 35 | bookDocument.author = bookDto.author; 36 | return delegateRepository 37 | .save(bookDocument) 38 | .thenEmpty(Mono.empty()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/adapters/secondary/mongodb/MongoBooksRepository.java: -------------------------------------------------------------------------------- 1 | package com.company.app.adapters.secondary.mongodb; 2 | 3 | import org.springframework.data.mongodb.repository.ReactiveMongoRepository; 4 | 5 | public interface MongoBooksRepository extends ReactiveMongoRepository { 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/adapters/secondary/mongodb/MongoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.company.app.adapters.secondary.mongodb; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories; 5 | 6 | @Configuration 7 | @EnableReactiveMongoRepositories 8 | class MongoConfiguration { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/application/BookCatalogApplication.java: -------------------------------------------------------------------------------- 1 | package com.company.app.application; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ComponentScan; 6 | 7 | @SpringBootApplication 8 | @ComponentScan("com.company.app") 9 | public class BookCatalogApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(BookCatalogApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/application/usecases/AddBookUseCase.java: -------------------------------------------------------------------------------- 1 | package com.company.app.application.usecases; 2 | 3 | import com.company.app.domain.model.Author; 4 | import com.company.app.domain.model.Book; 5 | import com.company.app.domain.model.Isbn; 6 | import com.company.app.domain.model.Title; 7 | import org.springframework.stereotype.Service; 8 | import reactor.core.publisher.Mono; 9 | 10 | @Service 11 | public class AddBookUseCase { 12 | private final AddBookPort addBookPort; 13 | 14 | public AddBookUseCase(AddBookPort addBookPort) { 15 | this.addBookPort = addBookPort; 16 | } 17 | 18 | public Response invoke(Request request) { 19 | BookDto bookDto = request.book; 20 | validateBook(bookDto); 21 | Mono addBook = addBookPort.addBook(bookDto); 22 | return new Response(addBook); 23 | } 24 | 25 | private void validateBook(BookDto bookDto) { 26 | Isbn isbn = new Isbn(bookDto.isbn); 27 | Title title = new Title(bookDto.title); 28 | Author author = new Author(bookDto.author); 29 | new Book(isbn, title, author); 30 | } 31 | 32 | public interface AddBookPort { 33 | Mono addBook(BookDto bookDto); 34 | } 35 | 36 | public static class Request { 37 | final BookDto book; 38 | 39 | public Request(BookDto book) { 40 | this.book = book; 41 | } 42 | } 43 | 44 | public static class Response { 45 | public final Mono addBook; 46 | 47 | Response(Mono addBook) { 48 | this.addBook = addBook; 49 | } 50 | } 51 | 52 | public static class BookDto { 53 | public String isbn; 54 | public String title; 55 | public String author; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/application/usecases/FindBooksUseCase.java: -------------------------------------------------------------------------------- 1 | package com.company.app.application.usecases; 2 | 3 | import org.springframework.stereotype.Service; 4 | import reactor.core.publisher.Flux; 5 | 6 | @Service 7 | public class FindBooksUseCase { 8 | private final FindBooksPort findBooksPort; 9 | 10 | public FindBooksUseCase(FindBooksPort findBooksPort) { 11 | this.findBooksPort = findBooksPort; 12 | } 13 | 14 | public Response invoke(Request request) { 15 | Flux allBooks = findBooksPort.findAllBooks(); 16 | return new Response(allBooks); 17 | } 18 | 19 | public interface FindBooksPort { 20 | Flux findAllBooks(); 21 | } 22 | 23 | public static class Request { 24 | } 25 | 26 | public static class Response { 27 | public final Flux books; 28 | 29 | Response(Flux books) { 30 | this.books = books; 31 | } 32 | } 33 | 34 | public static class BookDto { 35 | public String isbn; 36 | public String title; 37 | public String author; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/domain/model/Author.java: -------------------------------------------------------------------------------- 1 | package com.company.app.domain.model; 2 | 3 | import java.util.Objects; 4 | import java.util.StringJoiner; 5 | 6 | public class Author { 7 | private final String firstName; 8 | private final String lastName; 9 | 10 | public Author(String fullName) { 11 | if (fullName == null) { 12 | throw new IllegalArgumentException("Author's full name is required."); 13 | } 14 | if (!fullName.contains(" ")) { 15 | throw new IllegalArgumentException("Author's full name is required."); 16 | } 17 | this.firstName = fullName.substring(0, fullName.indexOf(' ')); 18 | this.lastName = fullName.substring(fullName.indexOf(' ')); 19 | } 20 | 21 | public String firstName() { 22 | return firstName; 23 | } 24 | 25 | public String lastName() { 26 | return lastName; 27 | } 28 | 29 | public String fullName() { 30 | return this.firstName + " " + this.lastName; 31 | } 32 | 33 | @Override 34 | public boolean equals(Object o) { 35 | if (this == o) return true; 36 | if (o == null || getClass() != o.getClass()) return false; 37 | Author author = (Author) o; 38 | return Objects.equals(firstName, author.firstName) && 39 | Objects.equals(lastName, author.lastName); 40 | } 41 | 42 | @Override 43 | public int hashCode() { 44 | return Objects.hash(firstName, lastName); 45 | } 46 | 47 | @Override 48 | public String toString() { 49 | return new StringJoiner(", ", Author.class.getSimpleName() + "[", "]") 50 | .add("firstName='" + firstName + "'") 51 | .add("lastName='" + lastName + "'") 52 | .toString(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/domain/model/Book.java: -------------------------------------------------------------------------------- 1 | package com.company.app.domain.model; 2 | 3 | import java.util.Objects; 4 | import java.util.StringJoiner; 5 | 6 | public class Book { 7 | private final Isbn isbn; 8 | private final Title title; 9 | private final Author author; 10 | 11 | public Book(Isbn isbn, Title title, Author author) { 12 | if (isbn == null) { 13 | throw new IllegalArgumentException("The book's ISBN is required."); 14 | } 15 | if (title == null) { 16 | throw new IllegalArgumentException("The book's title is required."); 17 | } 18 | if (author == null) { 19 | throw new IllegalArgumentException("The book's author is required."); 20 | } 21 | this.isbn = isbn; 22 | this.title = title; 23 | this.author = author; 24 | } 25 | 26 | public Isbn isbn() { 27 | return isbn; 28 | } 29 | 30 | public Title title() { 31 | return title; 32 | } 33 | 34 | public Author author() { 35 | return author; 36 | } 37 | 38 | @Override 39 | public boolean equals(Object o) { 40 | if (this == o) return true; 41 | if (o == null || getClass() != o.getClass()) return false; 42 | Book book = (Book) o; 43 | return Objects.equals(isbn, book.isbn) && 44 | Objects.equals(title, book.title) && 45 | Objects.equals(author, book.author); 46 | } 47 | 48 | @Override 49 | public int hashCode() { 50 | return Objects.hash(isbn, title, author); 51 | } 52 | 53 | @Override 54 | public String toString() { 55 | return new StringJoiner(", ", Book.class.getSimpleName() + "[", "]") 56 | .add("isbn=" + isbn) 57 | .add("title=" + title) 58 | .add("author=" + author) 59 | .toString(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/domain/model/Isbn.java: -------------------------------------------------------------------------------- 1 | package com.company.app.domain.model; 2 | 3 | import java.util.Objects; 4 | import java.util.StringJoiner; 5 | import java.util.regex.Pattern; 6 | 7 | public class Isbn { 8 | private static final Pattern ISBN10_ISBN13_PATTERN = Pattern.compile("^(\\d{9}|\\d{12})[\\d|X]$"); 9 | 10 | private final String value; 11 | 12 | public Isbn(String isbn) { 13 | if (!ISBN10_ISBN13_PATTERN.matcher(isbn).matches()) { 14 | throw new InvalidFormat(String.format("The ISBN format for \"%s\" is not valid.", isbn)); 15 | } 16 | this.value = isbn; 17 | } 18 | 19 | public String value() { 20 | return value; 21 | } 22 | 23 | @Override 24 | public boolean equals(Object o) { 25 | if (this == o) return true; 26 | if (o == null || getClass() != o.getClass()) return false; 27 | Isbn isbn = (Isbn) o; 28 | return Objects.equals(value, isbn.value); 29 | } 30 | 31 | @Override 32 | public int hashCode() { 33 | return Objects.hash(value); 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return new StringJoiner(", ", Isbn.class.getSimpleName() + "[", "]") 39 | .add("value='" + value + "'") 40 | .toString(); 41 | } 42 | 43 | public static class InvalidFormat extends RuntimeException { 44 | InvalidFormat(String message) { 45 | super(message); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/domain/model/Title.java: -------------------------------------------------------------------------------- 1 | package com.company.app.domain.model; 2 | 3 | import java.util.Objects; 4 | import java.util.StringJoiner; 5 | 6 | public class Title { 7 | private final String value; 8 | 9 | public Title(String value) { 10 | this.value = value; 11 | } 12 | 13 | public String value() { 14 | return value; 15 | } 16 | 17 | @Override 18 | public boolean equals(Object o) { 19 | if (this == o) return true; 20 | if (o == null || getClass() != o.getClass()) return false; 21 | Title title = (Title) o; 22 | return Objects.equals(value, title.value); 23 | } 24 | 25 | @Override 26 | public int hashCode() { 27 | return Objects.hash(value); 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return new StringJoiner(", ", Title.class.getSimpleName() + "[", "]") 33 | .add("value='" + value + "'") 34 | .toString(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/company/app/domain/services/BookDomainService.java: -------------------------------------------------------------------------------- 1 | package com.company.app.domain.services; 2 | 3 | import com.company.app.domain.model.Author; 4 | import com.company.app.domain.model.Book; 5 | 6 | public class BookDomainService { 7 | 8 | public void complexBusinessTransaction(Book book) { 9 | Author author = book.author(); 10 | String firstName = author.firstName(); 11 | String lastName = author.lastName(); 12 | // no-op 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8000 2 | -------------------------------------------------------------------------------- /src/main/resources/archunit_ignore_patterns.txt: -------------------------------------------------------------------------------- 1 | .*LegacyBooksApi.* 2 | -------------------------------------------------------------------------------- /src/test/http/books.addbook.http: -------------------------------------------------------------------------------- 1 | POST http://localhost:8000/books/ 2 | Content-Type: application/json 3 | 4 | { 5 | "isbn": "9780618260300", 6 | "title": "The Hobbit", 7 | "author": "J.R.R. Tolkien" 8 | } 9 | 10 | > {% 11 | client.test("Add book", function() { 12 | client.assert(response.status === 200, "Response status is not 200") 13 | }) 14 | %} 15 | 16 | ### 17 | -------------------------------------------------------------------------------- /src/test/http/books.getbooks.http: -------------------------------------------------------------------------------- 1 | GET http://localhost:8000/books/ 2 | Accept: application/json;charset=UTF-8 3 | 4 | > {% 5 | client.test("Get books", function() { 6 | client.assert(response.status === 200, "Response status is not 200") 7 | }) 8 | %} 9 | 10 | ### 11 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/application/BookCatalogApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.application; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class BookCatalogApplicationTest { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/AdaptersLayerComponentsTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.lang.ArchRule; 4 | import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; 5 | import org.junit.Test; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | public class AdaptersLayerComponentsTest extends ArchitectureTest { 9 | 10 | @Test 11 | public void configurationClassesShouldBeAnnotatedWithConfigurationAnnotation() { 12 | ArchRule rule = ArchRuleDefinition.classes() 13 | .that().haveSimpleNameEndingWith("Configuration") 14 | .should().beAnnotatedWith(Configuration.class); 15 | rule.check(classes); 16 | } 17 | 18 | @Test 19 | public void noClassesWithConfigurationAnnotationShouldResideOutsideOfAdaptersLayerPackages() { 20 | ArchRule rule = ArchRuleDefinition.noClasses() 21 | .that().areAnnotatedWith(Configuration.class) 22 | .should().resideOutsideOfPackage(ADAPTERS_LAYER_PACKAGES); 23 | rule.check(classes); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/ApplicationComponentsTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.core.domain.JavaClass; 4 | import com.tngtech.archunit.core.domain.JavaClassList; 5 | import com.tngtech.archunit.core.domain.JavaMethod; 6 | import com.tngtech.archunit.lang.ArchCondition; 7 | import com.tngtech.archunit.lang.ArchRule; 8 | import com.tngtech.archunit.lang.ConditionEvents; 9 | import com.tngtech.archunit.lang.SimpleConditionEvent; 10 | import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; 11 | import org.junit.Test; 12 | import org.springframework.stereotype.Service; 13 | 14 | import java.util.Set; 15 | import java.util.function.Predicate; 16 | 17 | public class ApplicationComponentsTest extends ArchitectureTest { 18 | 19 | @Test 20 | public void useCaseClassesShouldBeAnnotatedWithServiceAnnotation() { 21 | ArchRule rule = ArchRuleDefinition.classes() 22 | .that().haveSimpleNameEndingWith("UseCase") 23 | .should().beAnnotatedWith(Service.class); 24 | rule.check(classes); 25 | } 26 | 27 | @Test 28 | public void noUseCaseClassesShouldResideOutsideTheApplicationLayer() { 29 | ArchRule rule = ArchRuleDefinition.noClasses() 30 | .that().haveSimpleNameEndingWith("UseCase") 31 | .should().resideOutsideOfPackage(APPLICATION_LAYER_PACKAGES); 32 | rule.check(classes); 33 | } 34 | 35 | @Test 36 | public void noClassesWithServiceAnnotationShouldResideOutsideTheApplicationLayer() { 37 | ArchRule rule = ArchRuleDefinition.noClasses() 38 | .that().areAnnotatedWith(Service.class) 39 | .should().resideOutsideOfPackage(APPLICATION_LAYER_PACKAGES); 40 | rule.check(classes); 41 | } 42 | 43 | @Test 44 | public void useCaseClassesShouldHaveAnInvokeMethodWithASingleRequestParameterAndAResponseReturnType() { 45 | ArchRule rule = ArchRuleDefinition.classes() 46 | .that().haveSimpleNameEndingWith("UseCase") 47 | .should(new HaveAnInvokeMethodWithASingleRequestParameterAndAResponseReturnType()); 48 | rule.check(classes); 49 | } 50 | 51 | class HaveAnInvokeMethodWithASingleRequestParameterAndAResponseReturnType extends ArchCondition { 52 | 53 | HaveAnInvokeMethodWithASingleRequestParameterAndAResponseReturnType() { 54 | super("have an 'invoke' method with a single Request parameter and a Response return type"); 55 | } 56 | 57 | @Override 58 | public void check(JavaClass clazz, ConditionEvents events) { 59 | Set methods = clazz.getMethods(); 60 | Predicate hasMethodNamedInvoke = method -> method.getName().equals("invoke"); 61 | if (methods.stream().filter(hasMethodNamedInvoke).count() != 1) { 62 | events.add(SimpleConditionEvent.violated(clazz, "${clazz.simpleName} does not have a single 'invoke' method")); 63 | return; 64 | } 65 | methods.stream().filter(hasMethodNamedInvoke).findFirst().ifPresent(invokeMethod -> { 66 | JavaClassList parameters = invokeMethod.getRawParameterTypes(); 67 | if (parameters.size() != 1 || parameters.stream().noneMatch(it -> it.isInnerClass() && it.getSimpleName().equals("Request"))) { 68 | events.add(SimpleConditionEvent.violated(invokeMethod, "${clazz.simpleName}: method 'invoke' does not have a single parameter that is named 'request' and of inner-class type 'Request'")); 69 | } 70 | JavaClass returnType = invokeMethod.getRawReturnType(); 71 | if (!returnType.isInnerClass() || !returnType.getSimpleName().equals("Response")) { 72 | events.add(SimpleConditionEvent.violated(invokeMethod, "${clazz.simpleName}: method 'invoke' does not have a return type that is of inner-class type 'Response'")); 73 | } 74 | }); 75 | } 76 | 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/ArchitectureTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.core.domain.JavaClasses; 4 | import com.tngtech.archunit.core.importer.ClassFileImporter; 5 | import com.tngtech.archunit.core.importer.ImportOption; 6 | import org.junit.BeforeClass; 7 | 8 | public abstract class ArchitectureTest { 9 | static final String DOMAIN_LAYER_PACKAGES = "com.company.app.domain.."; 10 | static final String APPLICATION_LAYER_PACKAGES = "com.company.app.application.."; 11 | static final String ADAPTERS_LAYER_PACKAGES = "com.company.app.adapters.."; 12 | static final String PRIMARY_ADAPTERS_PACKAGES = "com.company.app.adapters.primary.."; 13 | static final String SECONDARY_ADAPTERS_PACKAGES = "com.company.app.adapters.secondary.."; 14 | 15 | static JavaClasses classes; 16 | 17 | @BeforeClass 18 | public static void setUp() { 19 | classes = new ClassFileImporter() 20 | .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) 21 | .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_ARCHIVES) 22 | .importPackages("com.company.app"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/DomainComponentsTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.lang.ArchRule; 4 | import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; 5 | import org.junit.Test; 6 | 7 | public class DomainComponentsTest extends ArchitectureTest { 8 | 9 | @Test 10 | public void domainClassesShouldOnlyBeAccessedByOtherDomainClassesOrTheApplicationLayer() { 11 | ArchRule rule = ArchRuleDefinition.classes() 12 | .that().resideInAPackage(DOMAIN_LAYER_PACKAGES) 13 | .should().onlyBeAccessed().byAnyPackage(DOMAIN_LAYER_PACKAGES, APPLICATION_LAYER_PACKAGES); 14 | rule.check(classes); 15 | } 16 | 17 | @Test 18 | public void domainClassesShouldOnlyDependOnDomainOrStdLibClasses() { 19 | ArchRule rule = ArchRuleDefinition.classes() 20 | .that().resideInAPackage(DOMAIN_LAYER_PACKAGES) 21 | .should().onlyDependOnClassesThat().resideInAnyPackage(DOMAIN_LAYER_PACKAGES, "java.."); 22 | rule.check(classes); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/GeneralCodingRulesTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.lang.ArchRule; 4 | import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; 5 | import com.tngtech.archunit.library.GeneralCodingRules; 6 | import org.junit.Test; 7 | 8 | public class GeneralCodingRulesTest extends ArchitectureTest { 9 | 10 | @Test 11 | public void noClassesShouldUseStandardStreams() { 12 | ArchRule rule = ArchRuleDefinition.noClasses() 13 | .should(GeneralCodingRules.ACCESS_STANDARD_STREAMS); 14 | rule.check(classes); 15 | } 16 | 17 | @Test 18 | public void noClassesShouldThrowGenericExceptions() { 19 | ArchRule rule = ArchRuleDefinition.noClasses() 20 | .should(GeneralCodingRules.THROW_GENERIC_EXCEPTIONS); 21 | rule.check(classes); 22 | } 23 | 24 | @Test 25 | public void noClassesShouldUseStandardLogging() { 26 | ArchRule rule = ArchRuleDefinition.noClasses() 27 | .should(GeneralCodingRules.USE_JAVA_UTIL_LOGGING); 28 | rule.check(classes); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/LayeredArchitectureTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.lang.ArchRule; 4 | import com.tngtech.archunit.library.Architectures; 5 | import org.junit.Test; 6 | 7 | public class LayeredArchitectureTest extends ArchitectureTest { 8 | 9 | private static final String DOMAIN_LAYER = "domain layer"; 10 | private static final String APPLICATION_LAYER = "application layer"; 11 | private static final String ADAPTERS_LAYER = "adapters layer"; 12 | 13 | private static Architectures.LayeredArchitecture portsAndAdaptersArchitecture = Architectures 14 | .layeredArchitecture() 15 | .layer(DOMAIN_LAYER).definedBy(DOMAIN_LAYER_PACKAGES) 16 | .layer(APPLICATION_LAYER).definedBy(APPLICATION_LAYER_PACKAGES) 17 | .layer(ADAPTERS_LAYER).definedBy(ADAPTERS_LAYER_PACKAGES); 18 | 19 | @Test 20 | public void domainLayerShouldOnlyBeAccessedByApplicationLayer() { 21 | ArchRule rule = portsAndAdaptersArchitecture.whereLayer(DOMAIN_LAYER) 22 | .mayOnlyBeAccessedByLayers(APPLICATION_LAYER); 23 | rule.check(classes); 24 | } 25 | 26 | @Test 27 | public void applicationLayerMayOnlyBeAccessedByAdaptersLayer() { 28 | ArchRule rule = portsAndAdaptersArchitecture 29 | .whereLayer(APPLICATION_LAYER) 30 | .mayOnlyBeAccessedByLayers(ADAPTERS_LAYER); 31 | rule.check(classes); 32 | } 33 | 34 | @Test 35 | public void adaptersLayerShouldNotBeAccessedByAnyLayer() { 36 | ArchRule rule = portsAndAdaptersArchitecture.whereLayer(ADAPTERS_LAYER) 37 | .mayNotBeAccessedByAnyLayer(); 38 | rule.check(classes); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/PrimaryAdaptersComponentsTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.lang.ArchRule; 4 | import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; 5 | import org.junit.Test; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | public class PrimaryAdaptersComponentsTest extends ArchitectureTest { 10 | 11 | @Test 12 | public void controllerClassesShouldBeAnnotatedWithControllerOrRestControllerAnnotation() { 13 | ArchRule rule = ArchRuleDefinition.classes() 14 | .that().haveSimpleNameEndingWith("Controller") 15 | .should().beAnnotatedWith(Controller.class) 16 | .orShould().beAnnotatedWith(RestController.class); 17 | rule.check(classes); 18 | } 19 | 20 | @Test 21 | public void noClassesWithControllerOrRestControllerAnnotationShouldResideOutsideOfPrimaryAdaptersPackages() { 22 | ArchRule rule = ArchRuleDefinition.noClasses() 23 | .that().areAnnotatedWith(Controller.class) 24 | .or().areAnnotatedWith(RestController.class) 25 | .should().resideOutsideOfPackage(PRIMARY_ADAPTERS_PACKAGES); 26 | rule.check(classes); 27 | } 28 | 29 | @Test 30 | public void controllerClassesShouldNotDependOnEachOther() { 31 | ArchRule rule = ArchRuleDefinition.noClasses() 32 | .that().haveSimpleNameEndingWith("Controller") 33 | .should().dependOnClassesThat().haveSimpleNameEndingWith("Controller"); 34 | rule.check(classes); 35 | } 36 | 37 | @Test 38 | public void publicControllerMethodsShouldBeAnnotatedWithARequestMapping() { 39 | ArchRule rule = ArchRuleDefinition.methods() 40 | .that().arePublic() 41 | .and().areDeclaredInClassesThat().resideInAPackage("..adapters.primary.web..") 42 | .and().areDeclaredInClassesThat().haveSimpleNameEndingWith("Controller") 43 | .and().areDeclaredInClassesThat().areAnnotatedWith(Controller.class) 44 | .or().areDeclaredInClassesThat().areAnnotatedWith(RestController.class) 45 | .should().beAnnotatedWith(RequestMapping.class) 46 | .orShould().beAnnotatedWith(GetMapping.class) 47 | .orShould().beAnnotatedWith(PostMapping.class) 48 | .orShould().beAnnotatedWith(PatchMapping.class) 49 | .orShould().beAnnotatedWith(DeleteMapping.class); 50 | rule.check(classes); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/SecondaryAdaptersComponentsTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.lang.ArchRule; 4 | import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; 5 | import org.junit.Test; 6 | import org.springframework.data.mongodb.core.mapping.Document; 7 | import org.springframework.stereotype.Repository; 8 | 9 | public class SecondaryAdaptersComponentsTest extends ArchitectureTest { 10 | 11 | @Test 12 | public void repositoryClassesShouldBeAnnotatedWithRepositoryAnnotation() { 13 | ArchRule rule = ArchRuleDefinition.classes() 14 | .that().haveSimpleNameEndingWith("Repository") 15 | .and().areNotInterfaces() 16 | .should().beAnnotatedWith(Repository.class); 17 | rule.check(classes); 18 | } 19 | 20 | @Test 21 | public void noClassesWithRepositoryAnnotationShouldResideOutsideOfSecondaryAdaptersPackages() { 22 | ArchRule rule = ArchRuleDefinition.noClasses() 23 | .that().areAnnotatedWith(Repository.class) 24 | .should().resideOutsideOfPackage(SECONDARY_ADAPTERS_PACKAGES); 25 | rule.check(classes); 26 | } 27 | 28 | @Test 29 | public void documentClassesShouldBeAnnotatedWithDocumentAnnotation() { 30 | ArchRule rule = ArchRuleDefinition.classes() 31 | .that().haveSimpleNameEndingWith("Document") 32 | .should().beAnnotatedWith(Document.class); 33 | rule.check(classes); 34 | } 35 | 36 | @Test 37 | public void noClassesWithDocumentAnnotationShouldResideOutsideOfSecondaryAdaptersPackages() { 38 | ArchRule rule = ArchRuleDefinition.noClasses() 39 | .that().areAnnotatedWith(Document.class) 40 | .should().resideOutsideOfPackage(SECONDARY_ADAPTERS_PACKAGES); 41 | rule.check(classes); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/SlicesTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.library.dependencies.SliceRule; 4 | import com.tngtech.archunit.library.dependencies.SlicesRuleDefinition; 5 | import org.junit.Test; 6 | 7 | public class SlicesTest extends ArchitectureTest { 8 | 9 | @Test 10 | public void layersShouldBeFreeOfCycles() { 11 | SliceRule rule = SlicesRuleDefinition.slices() 12 | .matching("com.company.app.(*)..") 13 | .should().beFreeOfCycles(); 14 | rule.check(classes); 15 | } 16 | 17 | @Test 18 | public void adaptersShouldNotDependOnEachOther() { 19 | SliceRule rule = SlicesRuleDefinition.slices() 20 | .matching("com.company.app.adapters.(**)") 21 | .should().notDependOnEachOther(); 22 | rule.check(classes); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/company/app/architecture/SpringCodingRulesTest.java: -------------------------------------------------------------------------------- 1 | package com.company.app.architecture; 2 | 3 | import com.tngtech.archunit.lang.ArchRule; 4 | import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; 5 | import org.junit.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.context.properties.ConfigurationProperties; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.stereotype.Repository; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | public class SpringCodingRulesTest extends ArchitectureTest { 15 | 16 | @Test 17 | public void springSingletonComponentsShouldOnlyHaveFinalFields() { 18 | ArchRule rule = ArchRuleDefinition.classes() 19 | .that().areAnnotatedWith(Service.class) 20 | .or().areAnnotatedWith(Component.class) 21 | .and().areNotAnnotatedWith(ConfigurationProperties.class) 22 | .or().areAnnotatedWith(Controller.class) 23 | .or().areAnnotatedWith(RestController.class) 24 | .or().areAnnotatedWith(Repository.class) 25 | .should().haveOnlyFinalFields(); 26 | rule.check(classes); 27 | } 28 | 29 | @Test 30 | public void springFieldDependencyInjectionShouldNotBeUsed() { 31 | ArchRule rule = ArchRuleDefinition.noFields() 32 | .should().beAnnotatedWith(Autowired.class); 33 | rule.check(classes); 34 | } 35 | } 36 | --------------------------------------------------------------------------------