├── .java-version ├── cheat-sheet.pdf ├── .gitpod.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── settings.gradle.kts ├── .gitattributes ├── src ├── main │ ├── resources │ │ ├── application.yml │ │ └── schema.sql │ └── java │ │ └── com │ │ └── agiletestingdays │ │ └── untangletestcode │ │ └── unicornservice │ │ ├── application │ │ ├── port │ │ │ ├── in │ │ │ │ ├── WriteUnicorn.java │ │ │ │ └── ReadUnicorn.java │ │ │ └── out │ │ │ │ └── UnicornStore.java │ │ └── service │ │ │ └── UnicornService.java │ │ ├── adapter │ │ ├── driven │ │ │ └── db │ │ │ │ ├── UnicornRepository.java │ │ │ │ ├── UnicornStoreAdapter.java │ │ │ │ └── UnicornEntity.java │ │ └── driving │ │ │ └── http │ │ │ ├── UnicornDto.java │ │ │ └── UnicornController.java │ │ ├── domain │ │ └── Unicorn.java │ │ └── Application.java └── test │ ├── java │ └── com │ │ └── agiletestingdays │ │ └── untangletestcode │ │ └── unicornservice │ │ ├── adapter │ │ ├── driven │ │ │ └── db │ │ │ │ └── UnicornRepositoryStub.java │ │ └── driving │ │ │ └── http │ │ │ └── UnicornControllerTest.java │ │ ├── test │ │ ├── TestDataManager.java │ │ └── UnicornTestDataBuilder.java │ │ ├── LocalTestApplication.java │ │ ├── domain │ │ └── UnicornTest.java │ │ ├── application │ │ └── service │ │ │ └── UnicornServiceTest.java │ │ └── ApplicationTest.java │ └── resources │ └── data.sql ├── .github ├── dependabot.yml └── workflows │ └── build.yml ├── RETROSPECTIVE.md ├── pre-commit ├── pre-push ├── .gitignore ├── gradlew.bat ├── README.md ├── TESTCODE_QUALITY_CRITERIA.md ├── .idea └── icon.svg ├── gradlew ├── LICENSE ├── TANGLES.md └── structure.svg /.java-version: -------------------------------------------------------------------------------- 1 | 21 2 | -------------------------------------------------------------------------------- /cheat-sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mkutz/untangle-your-spaghetti-test-code/HEAD/cheat-sheet.pdf -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | image: gitpod/workspace-java-21 2 | 3 | vscode: 4 | extensions: 5 | - vscjava.vscode-java-pack 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mkutz/untangle-your-spaghetti-test-code/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "untangle-your-spaghetti-test-code" 2 | 3 | System.setProperty("sonar.gradle.skipCompile", "true") 4 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # 2 | # https://help.github.com/articles/dealing-with-line-endings/ 3 | # 4 | # Linux start script should use lf 5 | /gradlew text eol=lf 6 | 7 | # These are Windows script files and should use crlf 8 | *.bat text eol=crlf 9 | 10 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:postgresql://localhost:5432/unicorn-service 4 | username: unicorn-service 5 | password: d4nc31ng0nR41nb0w5 6 | driverClassName: org.postgresql.Driver 7 | sql: 8 | init: 9 | mode: always 10 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gradle 4 | directory: / 5 | schedule: 6 | interval: weekly 7 | open-pull-requests-limit: 10 8 | - package-ecosystem: github-actions 9 | directory: / 10 | schedule: 11 | interval: weekly 12 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /src/main/resources/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE 2 | TABLE 3 | IF NOT EXISTS unicorns( 4 | id uuid NOT NULL, 5 | name VARCHAR NOT NULL, 6 | mane_color VARCHAR, 7 | horn_length INT, 8 | horn_diameter INT, 9 | date_of_birth DATE, 10 | PRIMARY KEY(id) 11 | ); 12 | -------------------------------------------------------------------------------- /RETROSPECTIVE.md: -------------------------------------------------------------------------------- 1 | # Retrospective 2 | 3 | Please take some minutes to answer the following questions: 4 | 5 | 1. What, if anything, did you learn today? 6 | 2. What, if anything, surprised you today? 7 | 3. What, if anything, will you do differently in the future? 8 | 9 | Please write your answers on sticky notes and stick them to the retrospective board. 10 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/application/port/in/WriteUnicorn.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.application.port.in; 2 | 3 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 4 | 5 | public interface WriteUnicorn { 6 | 7 | void createNewUnicorn(Unicorn unicorn); 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/agiletestingdays/untangletestcode/unicornservice/adapter/driven/db/UnicornRepositoryStub.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.adapter.driven.db; 2 | 3 | import java.util.UUID; 4 | import org.stubit.springdata.ListCrudRepositoryStub; 5 | 6 | public class UnicornRepositoryStub extends ListCrudRepositoryStub 7 | implements UnicornRepository {} 8 | -------------------------------------------------------------------------------- /pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | stagedFiles=$(git diff --staged --name-only) 4 | 5 | echo "🧹 Formatting code running spotlessApply…" 6 | ./gradlew spotlessApply 7 | if [ $? -ne 0 ]; then 8 | echo '… ✗ formatting failed' 9 | exit 1 10 | fi 11 | 12 | for file in $stagedFiles; do 13 | if test -f "$file"; then 14 | git add "$file" 15 | fi 16 | done 17 | 18 | echo "✓ formatting successful" 19 | exit 0 20 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/adapter/driven/db/UnicornRepository.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.adapter.driven.db; 2 | 3 | import java.util.UUID; 4 | import org.springframework.data.repository.ListCrudRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface UnicornRepository extends ListCrudRepository {} 9 | -------------------------------------------------------------------------------- /src/test/resources/data.sql: -------------------------------------------------------------------------------- 1 | TRUNCATE TABLE 2 | unicorns; 3 | 4 | INSERT 5 | INTO 6 | unicorns( 7 | id, 8 | name, 9 | mane_color, 10 | horn_length, 11 | horn_diameter, 12 | date_of_birth 13 | ) 14 | VALUES( 15 | '44eb6bdc-a0c9-4ce4-b28b-86d5950bcd23', 16 | 'Grace', 17 | 'RAINBOW', 18 | 42, 19 | 10, 20 | '1982-2-19' 21 | ); 22 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/application/port/in/ReadUnicorn.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.application.port.in; 2 | 3 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 4 | import java.util.List; 5 | import java.util.Optional; 6 | import java.util.UUID; 7 | 8 | public interface ReadUnicorn { 9 | 10 | List getAll(); 11 | 12 | Optional getById(UUID id); 13 | } 14 | -------------------------------------------------------------------------------- /pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,') 4 | protected_branches=( master main ) 5 | 6 | for i in "${protected_branches[@]}"; do 7 | if [[ $i == "$current_branch" ]]; then 8 | echo '⚠️ Attention! You are pushing to a protected branch. Running checks…' 9 | 10 | ./gradlew check 11 | if [ $? -ne 0 ]; then 12 | echo '✗ check failed' 13 | exit 1 14 | fi 15 | fi 16 | done 17 | 18 | echo "✓ check successful" 19 | exit 0 20 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/application/port/out/UnicornStore.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.application.port.out; 2 | 3 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 4 | import java.util.List; 5 | import java.util.Optional; 6 | import java.util.UUID; 7 | 8 | public interface UnicornStore { 9 | 10 | Optional findById(UUID id); 11 | 12 | List getAll(); 13 | 14 | Unicorn save(Unicorn unicorn); 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | **/build/ 3 | !src/**/build/ 4 | 5 | # Ignore Gradle GUI config 6 | gradle-app.setting 7 | 8 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 9 | !gradle-wrapper.jar 10 | 11 | # Avoid ignore Gradle wrappper properties 12 | !gradle-wrapper.properties 13 | 14 | # Cache of project 15 | .gradletasknamecache 16 | 17 | # Eclipse Gradle plugin generated files 18 | # Eclipse Core 19 | .project 20 | # JDT-specific (Eclipse Java Development Tools) 21 | .classpath 22 | 23 | # Ignore Idea project directory 24 | .idea/* 25 | 26 | # Add icon 27 | !.idea/icon.svg 28 | 29 | # Ignore Gradle build output directory 30 | build 31 | 32 | # VS Code 33 | bin/ 34 | settings.json 35 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/domain/Unicorn.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.domain; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Period; 5 | import java.util.UUID; 6 | 7 | public record Unicorn( 8 | UUID id, 9 | String name, 10 | ManeColor maneColor, 11 | Integer hornLength, 12 | Integer hornDiameter, 13 | LocalDate dateOfBirth) { 14 | 15 | public Unicorn { 16 | if (dateOfBirth.isAfter(LocalDate.now())) { 17 | throw new IllegalArgumentException("Future dates of birth are not supported!"); 18 | } 19 | } 20 | 21 | public Integer age() { 22 | return Period.between(dateOfBirth, LocalDate.now()).getYears(); 23 | } 24 | 25 | public enum ManeColor { 26 | BLUE, 27 | RED, 28 | GREEN, 29 | RAINBOW 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/Application.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice; 2 | 3 | import java.util.Locale; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 8 | import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; 9 | 10 | @SpringBootApplication 11 | @EnableJpaRepositories 12 | public class Application { 13 | 14 | static { 15 | Locale.setDefault(Locale.ENGLISH); 16 | } 17 | 18 | public static void main(String[] args) { 19 | SpringApplication.run(Application.class, args); 20 | } 21 | 22 | @Bean 23 | public LocalValidatorFactoryBean validator() { 24 | return new LocalValidatorFactoryBean(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/agiletestingdays/untangletestcode/unicornservice/test/TestDataManager.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.test; 2 | 3 | import com.agiletestingdays.untangletestcode.unicornservice.adapter.driven.db.UnicornEntity; 4 | import com.agiletestingdays.untangletestcode.unicornservice.adapter.driven.db.UnicornRepository; 5 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 6 | import org.springframework.beans.factory.annotation.Qualifier; 7 | import org.springframework.stereotype.Component; 8 | 9 | @Component 10 | public class TestDataManager { 11 | 12 | private final UnicornRepository repository; 13 | 14 | public TestDataManager(@Qualifier("unicornRepository") UnicornRepository repository) { 15 | this.repository = repository; 16 | } 17 | 18 | public TestDataManager withUnicorn(Unicorn unicorn) { 19 | repository.save(new UnicornEntity(unicorn)); 20 | return this; 21 | } 22 | 23 | public TestDataManager clear() { 24 | repository.deleteAll(); 25 | return this; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/adapter/driving/http/UnicornDto.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.adapter.driving.http; 2 | 3 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 4 | import com.fasterxml.jackson.annotation.JsonFormat; 5 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 6 | import jakarta.validation.constraints.Past; 7 | import java.time.LocalDate; 8 | import org.hibernate.validator.constraints.Range; 9 | 10 | @JsonIgnoreProperties(ignoreUnknown = true) 11 | public record UnicornDto( 12 | String id, 13 | String name, 14 | String maneColor, 15 | @Range(min = 1, max = 100) Integer hornLength, 16 | @Range(min = 1, max = 40) Integer hornDiameter, 17 | @Past @JsonFormat(pattern = "yyyy-MM-dd") LocalDate dateOfBirth) { 18 | public UnicornDto(Unicorn unicorn) { 19 | this( 20 | unicorn.id().toString(), 21 | unicorn.name(), 22 | unicorn.maneColor().name(), 23 | unicorn.hornLength(), 24 | unicorn.hornDiameter(), 25 | unicorn.dateOfBirth()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/adapter/driven/db/UnicornStoreAdapter.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.adapter.driven.db; 2 | 3 | import com.agiletestingdays.untangletestcode.unicornservice.application.port.out.UnicornStore; 4 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 5 | import java.util.List; 6 | import java.util.Optional; 7 | import java.util.UUID; 8 | import org.springframework.stereotype.Service; 9 | 10 | @Service 11 | public class UnicornStoreAdapter implements UnicornStore { 12 | 13 | UnicornRepository repository; 14 | 15 | public UnicornStoreAdapter(UnicornRepository repository) { 16 | this.repository = repository; 17 | } 18 | 19 | @Override 20 | public Optional findById(UUID id) { 21 | return repository.findById(id).map(UnicornEntity::toUnicorn); 22 | } 23 | 24 | @Override 25 | public List getAll() { 26 | return repository.findAll().stream().map(UnicornEntity::toUnicorn).toList(); 27 | } 28 | 29 | @Override 30 | public Unicorn save(Unicorn unicorn) { 31 | return repository.save(new UnicornEntity(unicorn)).toUnicorn(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/application/service/UnicornService.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.application.service; 2 | 3 | import com.agiletestingdays.untangletestcode.unicornservice.application.port.in.ReadUnicorn; 4 | import com.agiletestingdays.untangletestcode.unicornservice.application.port.in.WriteUnicorn; 5 | import com.agiletestingdays.untangletestcode.unicornservice.application.port.out.UnicornStore; 6 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 7 | import java.util.List; 8 | import java.util.Optional; 9 | import java.util.UUID; 10 | import org.springframework.stereotype.Service; 11 | 12 | @Service 13 | public class UnicornService implements ReadUnicorn, WriteUnicorn { 14 | 15 | private final UnicornStore store; 16 | 17 | public UnicornService(UnicornStore store) { 18 | this.store = store; 19 | } 20 | 21 | public List getAll() { 22 | return store.getAll(); 23 | } 24 | 25 | public Optional getById(UUID id) { 26 | return store.findById(id); 27 | } 28 | 29 | public void createNewUnicorn(Unicorn newUnicorn) { 30 | store.save(newUnicorn); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/agiletestingdays/untangletestcode/unicornservice/LocalTestApplication.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice; 2 | 3 | import java.time.Duration; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.testcontainers.service.connection.ServiceConnection; 7 | import org.springframework.context.annotation.Bean; 8 | import org.testcontainers.containers.PostgreSQLContainer; 9 | import org.testcontainers.containers.wait.strategy.Wait; 10 | import org.testcontainers.containers.wait.strategy.WaitAllStrategy; 11 | import org.testcontainers.junit.jupiter.Testcontainers; 12 | 13 | @SpringBootApplication 14 | @Testcontainers 15 | class LocalTestApplication { 16 | 17 | @Bean 18 | @ServiceConnection 19 | public PostgreSQLContainer postgreSQLContainer() { 20 | return new PostgreSQLContainer<>("postgres:16") 21 | // see 22 | // https://github.com/rancher-sandbox/rancher-desktop/issues/2609#issuecomment-1788871956 23 | .waitingFor( 24 | new WaitAllStrategy() 25 | .withStrategy(Wait.forListeningPort()) 26 | .withStrategy( 27 | Wait.forLogMessage(".*database system is ready to accept connections.*\\s", 2) 28 | .withStartupTimeout(Duration.ofSeconds(60)))); 29 | } 30 | 31 | public static void main(String[] args) { 32 | SpringApplication.from(Application::main).run(args); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build Main 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - solution/** 8 | paths-ignore: 9 | - '**.md' 10 | pull_request: 11 | branches: 12 | - main 13 | 14 | jobs: 15 | build: 16 | permissions: 17 | checks: write 18 | pull-requests: write 19 | contents: write 20 | 21 | runs-on: ubuntu-latest 22 | 23 | steps: 24 | 25 | - uses: actions/checkout@v6 26 | with: 27 | fetch-depth: 0 28 | 29 | - uses: actions/setup-java@v5 30 | with: 31 | java-version-file: .java-version 32 | distribution: temurin 33 | 34 | - name: Cache SonarCloud packages 35 | uses: actions/cache@v5 36 | with: 37 | path: ~/.sonar/cache 38 | key: ${{ runner.os }}-sonar 39 | restore-keys: ${{ runner.os }}-sonar 40 | - name: Cache Gradle packages 41 | uses: actions/cache@v5 42 | with: 43 | path: ~/.gradle/caches 44 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} 45 | restore-keys: ${{ runner.os }}-gradle 46 | 47 | - run: ./gradlew build jacocoTestReport sonar 48 | env: 49 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 50 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 51 | 52 | - name: Enable auto merge for Dependabot PRs 53 | run: gh pr merge --auto --rebase --delete-branch "${{ github.event.pull_request.html_url }}" 54 | if: ${{ github.event.pull_request.user.login == 'dependabot[bot]' }} 55 | env: 56 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 57 | -------------------------------------------------------------------------------- /src/test/java/com/agiletestingdays/untangletestcode/unicornservice/domain/UnicornTest.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.domain; 2 | 3 | import static java.util.UUID.randomUUID; 4 | import static org.assertj.core.api.Assertions.assertThat; 5 | 6 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn.ManeColor; 7 | import java.time.LocalDate; 8 | import org.junit.jupiter.api.Test; 9 | 10 | class UnicornTest { 11 | 12 | @Test 13 | void ageWorks() { 14 | var gilly = 15 | new Unicorn(randomUUID(), "Gilly", ManeColor.RED, 111, 11, LocalDate.now().minusYears(62)); 16 | 17 | assertThat(gilly.age()).isEqualTo(62); 18 | } 19 | 20 | @Test 21 | void ageWorksHereToo() { 22 | var gilly = 23 | new Unicorn( 24 | randomUUID(), 25 | "Gilly", 26 | ManeColor.RED, 27 | 111, 28 | 11, 29 | LocalDate.now().minusYears(62).minusMonths(1).minusDays(2)); 30 | 31 | assertThat(gilly.age()).isEqualTo(62); 32 | } 33 | 34 | @Test 35 | void ageWorksHereAlso() { 36 | var gilly = 37 | new Unicorn( 38 | randomUUID(), 39 | "Gilly", 40 | ManeColor.RED, 41 | 111, 42 | 11, 43 | LocalDate.now().minusYears(62).plusDays(1)); 44 | 45 | assertThat(gilly.age()).isEqualTo(61); 46 | } 47 | 48 | @Test 49 | void negativeAge() { 50 | try { 51 | new Unicorn(randomUUID(), "Gilly", ManeColor.RED, 111, 11, LocalDate.now().plusYears(2)); 52 | } catch (IllegalArgumentException e) { 53 | assertThat(e.getMessage()).isEqualTo("Future dates of birth are not supported!"); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/com/agiletestingdays/untangletestcode/unicornservice/application/service/UnicornServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.application.service; 2 | 3 | import static java.util.UUID.randomUUID; 4 | import static org.assertj.core.api.Assertions.assertThat; 5 | import static org.mockito.ArgumentMatchers.any; 6 | import static org.mockito.Mockito.mock; 7 | import static org.mockito.Mockito.times; 8 | import static org.mockito.Mockito.verify; 9 | import static org.mockito.Mockito.when; 10 | 11 | import com.agiletestingdays.untangletestcode.unicornservice.application.port.out.UnicornStore; 12 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 13 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn.ManeColor; 14 | import java.time.LocalDate; 15 | import java.util.List; 16 | import java.util.Optional; 17 | import java.util.UUID; 18 | import org.junit.jupiter.api.Test; 19 | 20 | class UnicornServiceTest { 21 | 22 | UnicornStore store = mock(UnicornStore.class); 23 | 24 | UnicornService unicornService = new UnicornService(store); 25 | 26 | @Test 27 | void getAllCallsRepository() { 28 | var unicorns = 29 | List.of( 30 | new Unicorn(randomUUID(), "Gilly", ManeColor.RED, 111, 11, LocalDate.of(1911, 11, 11)), 31 | new Unicorn(randomUUID(), "Garry", ManeColor.BLUE, 99, 9, LocalDate.of(1912, 12, 12))); 32 | when(store.getAll()).thenReturn(unicorns); 33 | 34 | var returnedUnicorns = unicornService.getAll(); 35 | 36 | assertThat(returnedUnicorns).containsAll(unicorns); 37 | verify(store, times(1)).getAll(); 38 | } 39 | 40 | @Test 41 | void getByIdCallsRepository() { 42 | var gilly = 43 | new Unicorn(randomUUID(), "Gilly", ManeColor.RED, 111, 11, LocalDate.of(1911, 11, 11)); 44 | when(store.findById(any(UUID.class))).thenReturn(Optional.of(gilly)); 45 | 46 | var returnedUnicorn = unicornService.getById(gilly.id()); 47 | 48 | assertThat(returnedUnicorn).isPresent().contains(gilly); 49 | verify(store, times(1)).findById(gilly.id()); 50 | } 51 | 52 | @Test 53 | void savingAUnicornWorks() { 54 | Unicorn garry = 55 | new Unicorn(randomUUID(), "Garry", ManeColor.BLUE, 99, 9, LocalDate.of(1912, 12, 12)); 56 | when(store.save(garry)).thenAnswer(invocation -> invocation.getArgument(0)); 57 | 58 | unicornService.createNewUnicorn(garry); 59 | 60 | verify(store, times(1)).save(garry); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/adapter/driven/db/UnicornEntity.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.adapter.driven.db; 2 | 3 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.Id; 6 | import jakarta.persistence.Table; 7 | import java.time.Instant; 8 | import java.time.LocalDate; 9 | import java.time.ZoneOffset; 10 | import java.util.UUID; 11 | 12 | @Entity 13 | @Table(name = "unicorns") 14 | public class UnicornEntity { 15 | 16 | @Id private UUID id; 17 | private String name; 18 | private String maneColor; 19 | private Integer hornLength; 20 | private Integer hornDiameter; 21 | private Instant dateOfBirth; 22 | 23 | public UnicornEntity() {} 24 | 25 | public UnicornEntity(Unicorn unicorn) { 26 | this.id = unicorn.id(); 27 | this.name = unicorn.name(); 28 | this.maneColor = unicorn.maneColor().name(); 29 | this.hornLength = unicorn.hornLength(); 30 | this.hornDiameter = unicorn.hornDiameter(); 31 | this.dateOfBirth = unicorn.dateOfBirth().atStartOfDay().toInstant(ZoneOffset.UTC); 32 | } 33 | 34 | public UUID getId() { 35 | return id; 36 | } 37 | 38 | public void setId(UUID id) { 39 | this.id = id; 40 | } 41 | 42 | public String getName() { 43 | return name; 44 | } 45 | 46 | public void setName(String name) { 47 | this.name = name; 48 | } 49 | 50 | public String getManeColor() { 51 | return maneColor; 52 | } 53 | 54 | public void setManeColor(String maneColor) { 55 | this.maneColor = maneColor; 56 | } 57 | 58 | public Integer getHornLength() { 59 | return hornLength; 60 | } 61 | 62 | public void setHornLength(Integer hornLength) { 63 | this.hornLength = hornLength; 64 | } 65 | 66 | public Integer getHornDiameter() { 67 | return hornDiameter; 68 | } 69 | 70 | public void setHornDiameter(Integer hornDiameter) { 71 | this.hornDiameter = hornDiameter; 72 | } 73 | 74 | public Instant getDateOfBirth() { 75 | return dateOfBirth; 76 | } 77 | 78 | public void setDateOfBirth(Instant dateOfBirth) { 79 | this.dateOfBirth = dateOfBirth; 80 | } 81 | 82 | public Unicorn toUnicorn() { 83 | return new Unicorn( 84 | id, 85 | name, 86 | Unicorn.ManeColor.valueOf(maneColor), 87 | hornLength, 88 | hornDiameter, 89 | LocalDate.ofInstant(dateOfBirth, ZoneOffset.UTC)); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Untangle Your Spaghetti Test Code 2 | 3 | [![Build](https://github.com/mkutz/untangle-your-spaghetti-test-code/actions/workflows/build.yml/badge.svg)](https://github.com/mkutz/untangle-your-spaghetti-test-code/actions/workflows/build.yml) 4 | [![Sonar Quality Gate](https://img.shields.io/sonar/quality_gate/mkutz_untangle-your-spaghetti-test-code?server=https%3A%2F%2Fsonarcloud.io)](https://sonarcloud.io/dashboard?id=mkutz_untangle-your-spaghetti-test-code) 5 | [![Sonar Coverage](https://img.shields.io/sonar/coverage/mkutz_untangle-your-spaghetti-test-code?server=http%3A%2F%2Fsonarcloud.io)](https://sonarcloud.io/dashboard?id=mkutz_untangle-your-spaghetti-test-code) 6 | 7 | 8 | ## Setup 9 | 10 | 1. [Login to GitHub](https://github.com/login) or [create an account](https://github.com/join). 11 | 2. If you don't have a local JDK 21 installation + an IDE: 12 | [create a new workspace at Gitpod](https://gitpod.io/#https://github.com/mkutz/untangle-your-spaghetti-test-code). 13 | This usually takes a little while, just be patient. 14 | 3. Open [ApplicationTest] from the file tree on the left. You should be able to execute the containing tests by clicking the green play button in the gutter. 15 | 16 | ## Structure 17 | 18 | ![Structure](structure.svg) 19 | 20 | 21 | ## Objectives 22 | 23 | Feel free to use the [Cheat Sheet] for inspiration. 24 | 25 | 1. Have a look at the [ApplicationTest]. 26 | 27 |
Brainstorm: Which problems do you see? 28 | 29 | - Do you understand **what's being tested**? 30 | - Is there a proper **arrange, act, assert structure** in the test cases? 31 | - Are the **names of test cases and variables** consistent?\ 32 | Does it help to understand implications of failures?\ 33 | Does it help to find the corresponding code? 34 | - Do you understand **how the test works technically**? 35 | - Do you see **where the test data is coming from**? 36 | - Which **code duplications** do you find?\ 37 | How would you reduce them? 38 | - Are the [Test Code Quality Criteria](TESTCODE_QUALITY_CRITERIA.md) applied? 39 | 40 |
41 | 42 | 2. Ensemble: Let's untangle it! 43 | 44 | 3. Have a look at the test at [UnicornServiceTest], [UnicornControllerTest] and [UnicornTest]. 45 | 46 |
Brainstorm: Which problems do you see? 47 | 48 | - Which **layer of the testing pyramid** is this test on?\ 49 | Is the layer appropriate for the test cases? 50 | Can we move tests here? 51 | 52 |
53 | 54 | ## References 55 | 56 | - [List of Tangles](TANGLES.md) 57 | - [Test Code Quality Criteria](TESTCODE_QUALITY_CRITERIA.md) 58 | - [Cheat Sheet] 59 | 60 | [ApplicationTest]: 61 | [UnicornControllerTest]: 62 | [UnicornServiceTest]: 63 | [UnicornTest]: 64 | [data.sql]: 65 | [Cheat Sheet]: 66 | [Baeldung on Instancio]: 67 | [Instancio]: 68 | -------------------------------------------------------------------------------- /src/main/java/com/agiletestingdays/untangletestcode/unicornservice/adapter/driving/http/UnicornController.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.adapter.driving.http; 2 | 3 | import static java.util.UUID.randomUUID; 4 | import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; 5 | 6 | import com.agiletestingdays.untangletestcode.unicornservice.application.port.in.ReadUnicorn; 7 | import com.agiletestingdays.untangletestcode.unicornservice.application.port.in.WriteUnicorn; 8 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 9 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn.ManeColor; 10 | import jakarta.validation.Validator; 11 | import java.util.List; 12 | import java.util.UUID; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.web.bind.annotation.GetMapping; 15 | import org.springframework.web.bind.annotation.PathVariable; 16 | import org.springframework.web.bind.annotation.PostMapping; 17 | import org.springframework.web.bind.annotation.RequestBody; 18 | import org.springframework.web.bind.annotation.RestController; 19 | import org.springframework.web.util.UriComponentsBuilder; 20 | 21 | @RestController("unicorns") 22 | public class UnicornController { 23 | 24 | private final ReadUnicorn readUnicorn; 25 | private final WriteUnicorn writeUnicorn; 26 | private final Validator validator; 27 | 28 | public UnicornController( 29 | ReadUnicorn readUnicorn, WriteUnicorn writeUnicorn, Validator validator) { 30 | this.readUnicorn = readUnicorn; 31 | this.writeUnicorn = writeUnicorn; 32 | this.validator = validator; 33 | } 34 | 35 | @GetMapping( 36 | path = {"unicorns", "unicorns/"}, 37 | produces = APPLICATION_JSON_VALUE) 38 | public ResponseEntity> getAllUnicorns() { 39 | return ResponseEntity.ok(readUnicorn.getAll().stream().map(UnicornDto::new).toList()); 40 | } 41 | 42 | @GetMapping(path = "unicorns/{id}", produces = APPLICATION_JSON_VALUE) 43 | public ResponseEntity getUnicorn(@PathVariable("id") UUID id) { 44 | return ResponseEntity.ofNullable(readUnicorn.getById(id).map(UnicornDto::new).orElse(null)); 45 | } 46 | 47 | @PostMapping( 48 | path = {"unicorns", "unicorns/"}, 49 | consumes = APPLICATION_JSON_VALUE, 50 | produces = APPLICATION_JSON_VALUE) 51 | public ResponseEntity postUnicorn( 52 | @RequestBody UnicornDto dto, UriComponentsBuilder uriComponentsBuilder) { 53 | var validationResult = validator.validate(dto); 54 | if (!validationResult.isEmpty()) { 55 | var violationMessages = 56 | validationResult.stream() 57 | .map( 58 | violation -> 59 | "%s %s".formatted(violation.getPropertyPath(), violation.getMessage())) 60 | .toList(); 61 | return ResponseEntity.badRequest().body(violationMessages); 62 | } 63 | 64 | var unicornId = randomUUID(); 65 | var unicorn = 66 | new Unicorn( 67 | unicornId, 68 | dto.name(), 69 | ManeColor.valueOf(dto.maneColor()), 70 | dto.hornLength(), 71 | dto.hornDiameter(), 72 | dto.dateOfBirth()); 73 | writeUnicorn.createNewUnicorn(unicorn); 74 | 75 | return ResponseEntity.created( 76 | uriComponentsBuilder.path("unicorns/").path(unicornId.toString()).build().toUri()) 77 | .body(new UnicornDto(unicorn)); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/java/com/agiletestingdays/untangletestcode/unicornservice/test/UnicornTestDataBuilder.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.test; 2 | 3 | import static java.util.UUID.randomUUID; 4 | import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; 5 | 6 | import com.agiletestingdays.untangletestcode.unicornservice.adapter.driven.db.UnicornEntity; 7 | import com.agiletestingdays.untangletestcode.unicornservice.adapter.driving.http.UnicornDto; 8 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 9 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn.ManeColor; 10 | import java.security.SecureRandom; 11 | import java.time.LocalDate; 12 | import java.util.UUID; 13 | 14 | public class UnicornTestDataBuilder { 15 | 16 | private final SecureRandom random = new SecureRandom(); 17 | 18 | private UUID id = randomUUID(); 19 | 20 | private String name = randomAlphabetic(8); 21 | 22 | private ManeColor maneColor = ManeColor.values()[random.nextInt(ManeColor.values().length)]; 23 | 24 | private Integer hornLength = random.nextInt(1, 101); 25 | 26 | private Integer hornDiameter = random.nextInt(1, 41); 27 | 28 | private LocalDate dateOfBirth = 29 | LocalDate.now() 30 | .minusDays(random.nextInt(0, 31)) 31 | .minusMonths(random.nextInt(0, 13)) 32 | .minusYears(random.nextInt(0, 101)); 33 | 34 | private UnicornTestDataBuilder() {} 35 | 36 | public static UnicornTestDataBuilder aUnicorn() { 37 | return new UnicornTestDataBuilder(); 38 | } 39 | 40 | public UnicornTestDataBuilder id(UUID id) { 41 | this.id = id; 42 | return this; 43 | } 44 | 45 | public UnicornTestDataBuilder name(String name) { 46 | this.name = name; 47 | return this; 48 | } 49 | 50 | public UnicornTestDataBuilder maneColor(ManeColor maneColor) { 51 | this.maneColor = maneColor; 52 | return this; 53 | } 54 | 55 | public UnicornTestDataBuilder hornLength(Integer hornLength) { 56 | this.hornLength = hornLength; 57 | return this; 58 | } 59 | 60 | public UnicornTestDataBuilder hornDiameter(Integer hornDiameter) { 61 | this.hornDiameter = hornDiameter; 62 | return this; 63 | } 64 | 65 | public UnicornTestDataBuilder dateOfBirth(LocalDate dateOfBirth) { 66 | this.dateOfBirth = dateOfBirth; 67 | return this; 68 | } 69 | 70 | public UnicornTestDataBuilder age(int age) { 71 | this.dateOfBirth = 72 | LocalDate.now() 73 | .minusDays(random.nextInt(0, 31)) 74 | .minusMonths(random.nextInt(0, 13)) 75 | .minusYears(random.nextInt(0, age)); 76 | return this; 77 | } 78 | 79 | public Unicorn build() { 80 | return new Unicorn(id, name, maneColor, hornLength, hornDiameter, dateOfBirth); 81 | } 82 | 83 | public UnicornDto buildDto() { 84 | return new UnicornDto(build()); 85 | } 86 | 87 | public UnicornEntity buildEntity() { 88 | return new UnicornEntity(build()); 89 | } 90 | 91 | public String buildJson() { 92 | return """ 93 | { 94 | "id": "%s", 95 | "name": "%s", 96 | "maneColor": "%s", 97 | "hornLength": %d, 98 | "hornDiameter": %d, 99 | "dateOfBirth": "%s" 100 | } 101 | """ 102 | .formatted(id, name, maneColor.name(), hornLength, hornDiameter, dateOfBirth); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /TESTCODE_QUALITY_CRITERIA.md: -------------------------------------------------------------------------------- 1 | # Testcode Quality Criteria 2 | 3 | ## Descriptive and Expressive Naming Conventions 4 | 5 | Test names should be both descriptive and expressive, clearly indicating the intent of the test and helping to quickly understand its purpose and expected outcome. This clarity is beneficial when reading test results or documentation. 6 | 7 | _Somewhat recommended for production code:_ Descriptive yet concise naming in production code is beneficial. It should be clear, encapsulate functionality, maintain modularity, and follow naming conventions. 8 | 9 | ## Clear and Relevant Setup (Arrange) 10 | 11 | In test automation, it's crucial to make the setup actions and initial state both clear and relevant, explicitly showing the conditions under which the test runs and including only the data necessary for understanding the test's purpose. This approach avoids hidden states or configurations, such as a prepopulated database that isn't directly referenced in the test code, and ensures that no extraneous information obfuscates what is being tested. 12 | 13 | _Not recommended for production code:_ Production code typically uses implicit setups like constructors and needs complete object initialization. Excessive detailing in setups can hinder maintainability. 14 | 15 | ## Eliminate Duplicate Setup Code 16 | 17 | Test code benefits from reducing duplication through shared setup methods or data builders. This practice keeps tests cleaner and easier to maintain. 18 | 19 | _Recommended for production code:_ Avoiding duplication is a core principle in all coding, but the means of achieving it may differ. In production, more sophisticated patterns like dependency injection may be preferred. 20 | 21 | ## Single Act in Tests 22 | 23 | A test should ideally perform a single action or operation, ensuring that there's only one reason for it to fail and making the cause of failure straightforward. 24 | 25 | _Not strictly applicable to production code:_ Production code often performs multiple actions in sequence as part of normal operation and is more concerned with handling the outcomes robustly. 26 | 27 | ## Concise and Focused Asserts 28 | 29 | Tests should have assertions that are targeted and clear, focusing on a single aspect of the test's outcome for easy debugging. 30 | 31 | _Not applicable to production code:_ Production code typically doesn't use assertions for flow control and instead employs exception handling and validation strategies. 32 | 33 | ## Follow Arrange-Act-Assert Pattern 34 | 35 | This pattern helps keep tests organized by clearly separating the preparation, the action under test, and the verification steps. 36 | 37 | _Not applicable to production code:_ While good organization is crucial, production code doesn't follow this pattern but rather focuses on clear workflows and error handling. 38 | 39 | ## Independent Test Cases 40 | 41 | Each test case should operate independently to avoid inter-test dependencies that could cause cascading failures. 42 | 43 | _Not directly applicable to production code:_ Production code often involves interdependent components working in a shared state, which requires careful management of state and transactions. 44 | 45 | ## Avoid Magic Values 46 | 47 | Tests should use named constants or data generators for values to make the purpose and origin of these values clear, reducing the risk of "magic numbers" or "magic strings." 48 | 49 | _Recommended for production code:_ Using well-named constants and avoiding magic values is a good practice to improve code readability and maintainability. 50 | 51 | ## Minimal Mocking 52 | 53 | Tests should use minimal mocking to avoid brittle tests that fail due to unrelated changes in the codebase. 54 | 55 | _Not applicable to production code:_ Mocking is a testing practice and is not used in production, where actual implementations of interfaces and services are used. 56 | 57 | ## Utilizing Helper Methods, Data Builders, Constants, and Data Generators 58 | 59 | In testing, leveraging helper methods, data builders, constants, and data generators can significantly simplify setup, enhancing both readability and maintenance. Helpers and builders facilitate the creation of complex objects, while constants and generators provide clear and unambiguous values, crucial for the transparency and predictability of tests. 60 | 61 | _Recommended for production code:_ These practices are equally beneficial in production code. Helper methods and builders aid in encapsulating complex constructions and configurations, and using named constants prevents the pitfalls of hardcoded values, leading to code that is both easier to understand and maintain. 62 | -------------------------------------------------------------------------------- /src/test/java/com/agiletestingdays/untangletestcode/unicornservice/adapter/driving/http/UnicornControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice.adapter.driving.http; 2 | 3 | import static java.util.UUID.randomUUID; 4 | import static org.assertj.core.api.Assertions.assertThat; 5 | import static org.mockito.ArgumentMatchers.any; 6 | import static org.mockito.Mockito.mock; 7 | import static org.mockito.Mockito.times; 8 | import static org.mockito.Mockito.verify; 9 | import static org.mockito.Mockito.when; 10 | 11 | import com.agiletestingdays.untangletestcode.unicornservice.application.port.in.ReadUnicorn; 12 | import com.agiletestingdays.untangletestcode.unicornservice.application.port.in.WriteUnicorn; 13 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn; 14 | import com.agiletestingdays.untangletestcode.unicornservice.domain.Unicorn.ManeColor; 15 | import jakarta.validation.Validator; 16 | import java.time.LocalDate; 17 | import java.util.List; 18 | import java.util.Optional; 19 | import java.util.UUID; 20 | import org.junit.jupiter.api.Test; 21 | import org.springframework.http.HttpStatusCode; 22 | import org.springframework.web.util.UriComponentsBuilder; 23 | 24 | class UnicornControllerTest { 25 | 26 | ReadUnicorn readUnicorn = mock(ReadUnicorn.class); 27 | WriteUnicorn writeUnicorn = mock(WriteUnicorn.class); 28 | Validator validator = mock(Validator.class); 29 | 30 | UnicornController unicornController = new UnicornController(readUnicorn, writeUnicorn, validator); 31 | 32 | @Test 33 | void getAllUnicornsReturnsAListOfUnicornDtos() { 34 | var gilly = 35 | new Unicorn( 36 | UUID.fromString("351d0356-6d5e-47d5-adbb-4909058fdf2f"), 37 | "Gilly", 38 | ManeColor.RED, 39 | 111, 40 | 11, 41 | LocalDate.of(1911, 11, 11)); 42 | var garry = 43 | new Unicorn(randomUUID(), "Garry", ManeColor.BLUE, 99, 9, LocalDate.of(1912, 12, 12)); 44 | var unicorns = List.of(gilly, garry); 45 | when(readUnicorn.getAll()).thenReturn(unicorns); 46 | 47 | var unicornsResponse = unicornController.getAllUnicorns(); 48 | 49 | assertThat(unicornsResponse.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(200)); 50 | assertThat(unicornsResponse.getBody()) 51 | .hasSize(2) 52 | .contains( 53 | new UnicornDto( 54 | gilly.id().toString(), 55 | gilly.name(), 56 | gilly.maneColor().toString(), 57 | gilly.hornLength(), 58 | gilly.hornDiameter(), 59 | gilly.dateOfBirth())) 60 | .contains( 61 | new UnicornDto( 62 | garry.id().toString(), 63 | garry.name(), 64 | garry.maneColor().toString(), 65 | garry.hornLength(), 66 | garry.hornDiameter(), 67 | garry.dateOfBirth())); 68 | 69 | verify(readUnicorn, times(1)).getAll(); 70 | } 71 | 72 | @Test 73 | void getSingleUnicornReturnsValidJson() { 74 | var gilly = 75 | new Unicorn(randomUUID(), "Gilly", ManeColor.RED, 111, 11, LocalDate.of(1911, 11, 11)); 76 | when(readUnicorn.getById(any(UUID.class))).thenReturn(Optional.of(gilly)); 77 | 78 | var unicornResponse = unicornController.getUnicorn(gilly.id()); 79 | 80 | assertThat(unicornResponse.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(200)); 81 | assertThat(unicornResponse.getBody()) 82 | .isNotNull() 83 | .isEqualTo( 84 | new UnicornDto( 85 | gilly.id().toString(), 86 | gilly.name(), 87 | gilly.maneColor().toString(), 88 | gilly.hornLength(), 89 | gilly.hornDiameter(), 90 | gilly.dateOfBirth())); 91 | verify(readUnicorn, times(1)).getById(gilly.id()); 92 | } 93 | 94 | @Test 95 | void getSingleUnicornsShouldReturnNullForUnknownId() { 96 | when(readUnicorn.getById(any(UUID.class))).thenReturn(Optional.empty()); 97 | 98 | var unicornResponse = unicornController.getUnicorn(randomUUID()); 99 | 100 | assertThat(unicornResponse.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(404)); 101 | assertThat(unicornResponse.getBody()).isNull(); 102 | } 103 | 104 | @Test 105 | void postingUnicornShouldReturnTheUnicornAndCreateItViaService() { 106 | var gillyDto = new UnicornDto(null, "Gilly", "RED", 111, 11, LocalDate.of(1911, 11, 11)); 107 | 108 | var createResponse = 109 | unicornController.postUnicorn(gillyDto, UriComponentsBuilder.newInstance()); 110 | 111 | assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(201)); 112 | assertThat(createResponse.getBody()) 113 | .isNotNull() 114 | .hasNoNullFieldsOrProperties() 115 | .hasFieldOrPropertyWithValue("name", gillyDto.name()) 116 | .hasFieldOrPropertyWithValue("maneColor", gillyDto.maneColor()) 117 | .hasFieldOrPropertyWithValue("hornLength", gillyDto.hornLength()) 118 | .hasFieldOrPropertyWithValue("hornDiameter", gillyDto.hornDiameter()) 119 | .hasFieldOrPropertyWithValue("dateOfBirth", gillyDto.dateOfBirth()); 120 | assertThat(createResponse.getHeaders()).containsKey("Location"); 121 | verify(writeUnicorn, times(1)).createNewUnicorn(any(Unicorn.class)); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /.idea/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 60 | -------------------------------------------------------------------------------- /src/test/java/com/agiletestingdays/untangletestcode/unicornservice/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.agiletestingdays.untangletestcode.unicornservice; 2 | 3 | import static java.util.Objects.requireNonNull; 4 | import static org.assertj.core.api.Assertions.assertThat; 5 | import static org.springframework.http.RequestEntity.post; 6 | 7 | import com.fasterxml.jackson.core.JsonProcessingException; 8 | import com.fasterxml.jackson.databind.ObjectMapper; 9 | import java.time.LocalDate; 10 | import java.time.format.DateTimeFormatter; 11 | import java.util.List; 12 | import java.util.Map; 13 | import org.junit.jupiter.api.Test; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.beans.factory.annotation.Value; 16 | import org.springframework.boot.test.context.SpringBootTest; 17 | import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; 18 | import org.springframework.boot.test.web.client.TestRestTemplate; 19 | import org.springframework.http.HttpStatus; 20 | import org.springframework.http.HttpStatusCode; 21 | import org.springframework.test.annotation.DirtiesContext; 22 | 23 | @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = LocalTestApplication.class) 24 | class ApplicationTest { 25 | 26 | @Value("http://localhost:${local.server.port}") 27 | String baseUrl; 28 | 29 | @Autowired TestRestTemplate restTemplate; 30 | @Autowired ObjectMapper objectMapper; 31 | 32 | @Test 33 | void getUnicornsWorksAndReturnsNonEmptyList() throws JsonProcessingException { 34 | var response = restTemplate.getForEntity("%s/unicorns".formatted(baseUrl), String.class); 35 | 36 | assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); 37 | 38 | var body = objectMapper.readTree(response.getBody()); 39 | 40 | assertThat(body).isNotNull(); 41 | assertThat(body.isArray()).isTrue(); 42 | assertThat(body.size()).isEqualTo(1); 43 | } 44 | 45 | @Test 46 | void getSingleUnicornWorksAndReturnsData() throws JsonProcessingException { 47 | var response = 48 | restTemplate.getForEntity( 49 | "%s/unicorns/%s".formatted(baseUrl, "44eb6bdc-a0c9-4ce4-b28b-86d5950bcd23"), 50 | String.class); 51 | var unicornData = objectMapper.readTree(response.getBody()); 52 | 53 | assertThat(unicornData.has("id")).isTrue(); 54 | assertThat(unicornData.get("id").asText()).isEqualTo("44eb6bdc-a0c9-4ce4-b28b-86d5950bcd23"); 55 | 56 | assertThat(unicornData.has("name")).isTrue(); 57 | assertThat(unicornData.get("name").asText()).isEqualTo("Grace"); 58 | 59 | assertThat(unicornData.has("maneColor")).isTrue(); 60 | assertThat(unicornData.get("maneColor").asText()).isEqualTo("RAINBOW"); 61 | 62 | assertThat(unicornData.has("hornLength")).isTrue(); 63 | assertThat(unicornData.get("hornLength").asInt()).isEqualTo(42); 64 | 65 | assertThat(unicornData.has("hornDiameter")).isTrue(); 66 | assertThat(unicornData.get("hornDiameter").asInt()).isEqualTo(10); 67 | 68 | assertThat(unicornData.has("dateOfBirth")).isTrue(); 69 | assertThat(unicornData.get("dateOfBirth").asText()).isEqualTo("1982-02-19"); 70 | } 71 | 72 | @Test 73 | @DirtiesContext 74 | void postNewUnicorn() { 75 | var garryJson = 76 | "{\"dateOfBirth\":\"1999-10-12\",\"hornDiameter\":11,\"hornLength\":37,\"maneColor\":\"BLUE\",\"name\":\"Garry\"}"; 77 | var response = 78 | restTemplate.exchange( 79 | post("%s/unicorns/".formatted(baseUrl)) 80 | .header("Content-Type", "application/json") 81 | .body(garryJson), 82 | String.class); 83 | 84 | assertThat(response.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(201)); 85 | assertThat(response.getHeaders().get("Location")).isNotNull().hasSize(1); 86 | 87 | var anotherResponse = 88 | restTemplate.getForEntity( 89 | requireNonNull(response.getHeaders().get("Location")).getFirst(), String.class); 90 | 91 | assertThat(anotherResponse.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(200)); 92 | } 93 | 94 | @Test 95 | @DirtiesContext 96 | void testHLZero() throws JsonProcessingException { 97 | var larryJson = 98 | objectMapper.writeValueAsString( 99 | Map.of( 100 | "name", 101 | "Larry", 102 | "maneColor", 103 | "BLUE", 104 | "hornLength", 105 | 0, 106 | "hornDiameter", 107 | 18, 108 | "dateOfBirth", 109 | "1999-10-12")); 110 | var response = 111 | restTemplate.exchange( 112 | post("%s/unicorns/".formatted(baseUrl)) 113 | .header("Content-Type", "application/json") 114 | .body(larryJson), 115 | List.class); 116 | 117 | assertThat(response.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(400)); 118 | assertThat(response.getHeaders().containsKey("Location")).isFalse(); 119 | assertThat(response.getBody()).contains("hornLength must be between 1 and 100"); 120 | } 121 | 122 | @Test 123 | @DirtiesContext 124 | void testHLTooMuch() throws JsonProcessingException { 125 | var larryJson = 126 | objectMapper.writeValueAsString( 127 | Map.of( 128 | "name", 129 | "Barry", 130 | "maneColor", 131 | "BLUE", 132 | "hornLength", 133 | 101, 134 | "hornDiameter", 135 | 18, 136 | "dateOfBirth", 137 | "1999-10-12")); 138 | var response = 139 | restTemplate.exchange( 140 | post("%s/unicorns/".formatted(baseUrl)) 141 | .header("Content-Type", "application/json") 142 | .body(larryJson), 143 | List.class); 144 | 145 | assertThat(response.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(400)); 146 | assertThat(response.getHeaders().containsKey("Location")).isFalse(); 147 | assertThat(response.getBody()).contains("hornLength must be between 1 and 100"); 148 | } 149 | 150 | @Test 151 | @DirtiesContext 152 | void testHDNotGiven() throws JsonProcessingException { 153 | var larryJson = 154 | objectMapper.writeValueAsString( 155 | Map.of( 156 | "name", 157 | "Jerry", 158 | "maneColor", 159 | "BLUE", 160 | "hornLength", 161 | 66, 162 | "hornDiameter", 163 | 0, 164 | "dateOfBirth", 165 | "1999-10-12")); 166 | var response = 167 | restTemplate.exchange( 168 | post("%s/unicorns/".formatted(baseUrl)) 169 | .header("Content-Type", "application/json") 170 | .body(larryJson), 171 | List.class); 172 | 173 | assertThat(response.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(400)); 174 | assertThat(response.getHeaders().containsKey("Location")).isFalse(); 175 | assertThat(response.getBody()).contains("hornDiameter must be between 1 and 40"); 176 | } 177 | 178 | @Test 179 | @DirtiesContext 180 | void testHDOver() throws JsonProcessingException { 181 | var larryJson = 182 | objectMapper.writeValueAsString( 183 | Map.of( 184 | "name", 185 | "Harry", 186 | "maneColor", 187 | "BLUE", 188 | "hornLength", 189 | 67, 190 | "hornDiameter", 191 | 42, 192 | "dateOfBirth", 193 | "1999-10-12")); 194 | var response = 195 | restTemplate.exchange( 196 | post("%s/unicorns/".formatted(baseUrl)) 197 | .header("Content-Type", "application/json") 198 | .body(larryJson), 199 | List.class); 200 | 201 | assertThat(response.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(400)); 202 | assertThat(response.getHeaders().containsKey("Location")).isFalse(); 203 | assertThat(response.getBody()).contains("hornDiameter must be between 1 and 40"); 204 | } 205 | 206 | @Test 207 | @DirtiesContext 208 | void testDOBFuture() throws JsonProcessingException { 209 | var larryJson = 210 | objectMapper.writeValueAsString( 211 | Map.of( 212 | "name", 213 | "Mary", 214 | "maneColor", 215 | "BLUE", 216 | "hornLength", 217 | 37, 218 | "hornDiameter", 219 | 11, 220 | "dateOfBirth", 221 | LocalDate.now().plusDays(1).format(DateTimeFormatter.ISO_DATE))); 222 | var response = 223 | restTemplate.exchange( 224 | post("%s/unicorns/".formatted(baseUrl)) 225 | .header("Content-Type", "application/json") 226 | .header("Accept-Language", "en") 227 | .body(larryJson), 228 | String.class); 229 | 230 | assertThat(response.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(400)); 231 | assertThat(response.getHeaders().containsKey("Location")).isFalse(); 232 | assertThat(response.getBody()).contains("dateOfBirth must be a past date"); 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /TANGLES.md: -------------------------------------------------------------------------------- 1 | # Tangles & Untangles 2 | 3 | ## Goal 4 | 5 | Test code is code.\ 6 | What's considered bad in production code, is bad in test code. 7 | 8 | Its intention should be immediately obvious.\ 9 | Its functionality shouldn't be obscured.\ 10 | Its results should be meaningful.\ 11 | Its failure causes should be easy to find. 12 | 13 | ## Tangles 14 | 15 | ### Hidden Arrange 16 | 17 | Sometimes our tests rely on a non-obvious setup. 18 | 19 | For example: the database implicitly gets set up with a test data set. The data is then used in the tests' asserts, but its source is not visible from the test itself. 20 | 21 | This is generally problematic as it divides the arrange steps from the act and assert steps that required them in the first place. 22 | Hence, it may hide potential failure causes. 23 | To refer to the example: when we add another dataset, any test that checks the number of datasets will fail. 24 | 25 | Untangle with 26 | 27 | - [Test Setup Helper Method](#test-setup-helper-method) 28 | - [Test Data Builder](#test-data-builder) 29 | - [Test Data Manager](#test-data-manager) 30 | 31 | ### Duplicate setup code 32 | 33 | Creating and setting up test objects is duplicated in multiple tests. 34 | 35 | First of all this is a code duplication, which is problematic in itself. 36 | When the code becomes outdated for any reason, we need to change it in all the places we copied it to. 37 | The duplication is probably longer than a reference to it would be, hence we add unnecessary lines of code. 38 | 39 | Untangle with 40 | 41 | - [Test Setup Helper Method](#test-setup-helper-method) 42 | - [Test Data Builder](#test-data-builder) 43 | 44 | ### Magic Values 45 | 46 | A magic value is basically some literal values appearing somewhere in the code without any hint why it was chosen or what it means. 47 | 48 | This may happen because you just needed some value to create an object or call a method. 49 | So you simply write `123` for an integer or `lorem ipsum` for a string. 50 | Both values may indicate randomness, but are they? 51 | Is `123` a representative of an integer, a positive integer, or a three-digit number? 52 | Is `lorem ipsum` chosen for its length, or does it indicate that the string cannot contain special characters or digits? 53 | 54 | It might be obvious to you now, but it won't be to everyone. 55 | Of course, we can easily check by changing the value or checking the other test cases. 56 | The problem is that this makes understanding the test case is made harder for no goo reason! 57 | 58 | ```java 59 | var gilly = new Unicorn( 60 | "351d0356-6d5e-47d5-adbb-4909058fdf2f", // ?? 61 | "Gilly", // I guess we use this all the time? 62 | ManeColor.RED, // Why not BLUE? 63 | 154, // Is this important? 64 | 12, // Why 12? 65 | today().minusYears(62).plusDays(1) 66 | ); 67 | 68 | assertThat(gilly.age()) 69 | .isEqualTo(61); // Not 62?!? 70 | ``` 71 | 72 | Untangle with 73 | 74 | - [Test Setup Helper Method](#test-setup-helper-method) 75 | - [Explicit Constants](#explicit-constants) 76 | - [Test Data Builder](#test-data-builder) 77 | 78 | ### Long Arrange 79 | 80 | When dealing with big data objects, we need to construct these objects to arrange our tests. 81 | Quite often only few of the set properties are actually relevant for the test at hand. 82 | The other set properties are actually just set to satisfy the constructor of the class and often use [Magic Values](#magic-values). 83 | 84 | This is a problem as it makes spotting the difference of the test case compared to the others harder and hence obscures the intention of the case. 85 | 86 | ```java 87 | var gilly = new Unicorn( 88 | randomUUID(), 89 | "Gilly", 90 | ManeColor.RED, 91 | 111, 92 | 11, 93 | today().minusYears(62) // this is only relevant line! 94 | ); 95 | 96 | assertThat(gilly.age()).isEqualTo(62); 97 | ``` 98 | 99 | Untangle with 100 | 101 | - [Test Setup Helper Method](#test-setup-helper-method) 102 | - [Test Data Builder](#test-data-builder) 103 | 104 | ### Long Assert 105 | 106 | Verifying big data objects can lead to a lot of simple assertions, which make the intention of the test hard to understand. 107 | 108 | ```java 109 | var response = restTemplate 110 | .getForEntity(url, String.class); 111 | 112 | var data = objectMapper 113 | .readTree(response.getBody()); 114 | 115 | assertThat(data.get("id").asText()) 116 | .isEqualTo("4711"); 117 | assertThat(data.get("name").asText()) 118 | .isEqualTo("Grace"); 119 | assertThat(data.get("maneColor").asText()) 120 | .isEqualTo("RAINBOW"); 121 | assertThat(data.get("hornLength").asInt()) 122 | .isEqualTo(42); 123 | assertThat(data.get("hornDiameter").asInt()) 124 | .isEqualTo(10); 125 | assertThat(data.get("dateOfBirth").asText()) 126 | .isEqualTo("1982-02-19"); 127 | ``` 128 | 129 | Untangle with 130 | 131 | - [Verification Method](#verification-method) 132 | - [Test Data Builder](#test-data-builder) (asserting the result is equal to a built expected object) 133 | 134 | ### Interdependent Test Cases 135 | 136 | Test cases can be written in a way that they rely on other cases. 137 | Either by intention due to a very cumbersome setup, or accidentally when you assume the result of a series of test is actually the result of the arrange phase. 138 | 139 | This is especially harmful as changing or removing one test case can make multiple other cases fail that dependent on it. 140 | 141 | Untangle with 142 | 143 | - [Test Data Manger](#test-data-manager) 144 | 145 | ### Multiple Acts 146 | 147 | When tests have multiple interactions with the unit under test, they usually have a lot of possible reasons to fail. 148 | This makes a failing test an ambiguous signal. 149 | 150 | ```java 151 | var postResponse = restTemplate 152 | .postForEntity(url, unicorn, String.class); // 1st ACT 153 | 154 | assertThat(response.getStatusCode()) 155 | .isEqualTo(HttpStatusCode.valueOf(201)); 156 | 157 | var location = postResponse 158 | .getHeaders().get("Location")).get(0); 159 | 160 | var getResponse = restTemplate 161 | .getForEntity(location, String.class); // 2nd ACT 162 | 163 | assertThat(getResponse.getStatusCode()) 164 | .isEqualTo(HttpStatusCode.valueOf(200)); 165 | ``` 166 | 167 | Note that this tangle might be a reasonable tradeoff in case the preparation takes very long. 168 | E.g. in complex GUI tests. 169 | 170 | Untangle with 171 | 172 | - [Split by Assumptions](#split-with-assumptions) 173 | - [Test Data Manager](#test-data-manager) 174 | 175 | ### Lying Test Case Names 176 | 177 | Test case names are not executable code. 178 | Hence, their correctness is not checked automatically like the actual test code. 179 | 180 | They often help though, to understand the general intention of a test case, and they are usually the data we get from test reports. 181 | 182 | Often test case names are copy-pasted from other tests, and often we fail adjust them when the content of the test case changes. 183 | 184 | ```java 185 | @Test 186 | void postInvalidUnicornYieldsA500Response() { 187 | var response = restTemplate 188 | .postForEntity(url, String.class); 189 | 190 | assertThat(response.getStatusCode()) 191 | .isEqualTo(HttpStatusCode.valueOf(400)); // name says 500! 192 | assertThat(response 193 | .getHeaders() 194 | .containsKey("Location")) 195 | .isFalse(); 196 | assertThat(response.getBody()) 197 | .contains("invalid unicorn"); 198 | } 199 | ``` 200 | 201 | Untangle with 202 | 203 | - [Expressive Test Case Naming](#expressive--consistent-test-case-names) 204 | 205 | ## Untangles 206 | 207 | ### Arrange Act Assert (Given When Then) 208 | 209 | Tests should always have three parts (at most): 210 | 211 | 1. __Arrange__ (or given) sets everything up for the test. 212 | The code should be concise and focus on what makes the test case different from others. 213 | 214 | 2. __Act__ (or when) contains the interaction that's actually being tested. 215 | This part should be one line/one interaction with the unit under test. 216 | Otherwise, the number of potential outcomes quickly become confusing. 217 | 218 | 3. __Assert__ (or then) checks the effects of act. 219 | Ideally this only checks one aspect of the result, so the test can only fail for one obvious reason. 220 | 221 | Note that arrange is optional. 222 | Act and assert can be combined in one line of code. 223 | 224 | See also [Martin Fowler on GivenWhenThen](https://martinfowler.com/bliki/GivenWhenThen.html) 225 | 226 | ## Expressive & Consistent Test Case Names 227 | 228 | Choose a naming scheme that makes test case names clear, expressive, concise, unambiguous, and easily understandable. 229 | 230 | Useful components of a naming scheme are ``, ``, and ``. 231 | 232 | Any naming scheme is better than no naming scheme at all! 233 | 234 | ```java 235 | class Test { 236 | void _() { 237 | … // see code for 238 | } 239 | } 240 | ``` 241 | 242 | Other suggestions: 243 | 244 | - `__` 245 | - `__` 246 | - `_should__if_` 247 | - `given__when__then_` 248 | 249 | See also 250 | 251 | - [Alex Zhukovich's suggestions](https://ui-testing.academy/naming/naming-conventions-for-test-cases/) 252 | - [Michael Kutz on naming tests for maintainability](https://michakutz.medium.com/how-to-name-tests-for-maintainability-c11af89f0f04) 253 | 254 | ### Split with Assumptions 255 | 256 | If you find [Multiple Acts](#multiple-acts) in a test case, you might want to split it with Assumptions. 257 | Copy the test, remove the second act from the original, and replace the copy's assertion code with an assumption. 258 | 259 | An assumption will not fail, but skip the test. 260 | Hence, the original test case will tell us about the error, but the case depending on it will simply be skipped. 261 | 262 | ```java 263 | @Test 264 | void POST_new_unicorn() { 265 | var response = restTemplate 266 | .postForEntity(url, unicorn, String.class); 267 | 268 | assertThat(response.getStatusCode()) 269 | .isEqualTo(HttpStatusCode.valueOf(201)); 270 | assertThat(response 271 | .getHeaders().contains("Location")).isTrue() 272 | } 273 | 274 | @Test 275 | void GET_location_header() { 276 | var postResponse = restTemplate 277 | .postForEntity(url, unicorn, String.class); 278 | // assume what's asserted somewhere else 279 | assumeThat(response.getStatusCode()) 280 | .isEqualTo(HttpStatusCode.valueOf(201)); 281 | var location = postResponse 282 | .getHeaders().get("Location")).get(0); 283 | 284 | var getResponse = restTemplate 285 | .getForEntity(location, String.class); 286 | 287 | assertThat(getResponse.getStatusCode()) 288 | .isEqualTo(HttpStatusCode.valueOf(200)); 289 | } 290 | ``` 291 | 292 | See also 293 | 294 | - [Assumptions in JUnit](https://junit.org/junit5/docs/current/user-guide/#writing-tests-assumptions) 295 | - [AssertJ Assumptions](https://assertj.github.io/doc/#assertj-core-assumptions) 296 | 297 | ### Test Data Manager 298 | 299 | A test data manager directly interacts with the database to inject wanted test data. 300 | 301 | ```java 302 | testDataManager.withUnicorn(unicorn); 303 | 304 | var respose = restTemplate 305 | .getForEnitiy(url, String.class); 306 | 307 | assertThat(response.getBody()) 308 | .contains(unicorn.name()); 309 | ``` 310 | 311 | It can also be used to clean up and hence allows to test no data scenarios. 312 | 313 | ```java 314 | testDataManager.withNoUnicorns(); 315 | 316 | var respose = restTemplate 317 | .getForEnitiy(url, List.class); 318 | 319 | assertThat(response.getBody()) 320 | .isEmpty(); 321 | ``` 322 | 323 | ## Explicit Constants 324 | 325 | Explicitly named test data constants can help to understand the test code a lot. 326 | Choose good names, e.g. prefix with `SOME_` to express that the actual value doesn't matter. 327 | 328 | ```java 329 | var someUnicorn = 330 | new Unicorn( 331 | SOME_ID, // "some" value => doesn't matter 332 | SOME_UNICORN_NAME, 333 | SOME_MANE_COLOR, 334 | SOME_VALID_HORN_LENGTH, 335 | SOME_VALID_HORN_DIAMETER, 336 | today.minusYears(62)); // this matters 337 | ``` 338 | 339 | You might want to keep these constants in a separate class (e.g. `TestDataConstants`) to make it accessible to all test cases. 340 | 341 | See also [Random Data Generators](#random-data-generators) 342 | 343 | ### Random Data Generators 344 | 345 | Use random data generators for test data. 346 | 347 | This may be necessary to resolve dependencies between tests (e.g. to ensure uniqueness of IDs). 348 | 349 | It can also technically underline that the concrete value should not matter for the test. 350 | 351 | ```java 352 | var someUnicorn = 353 | new Unicorn( 354 | randomUUID(), // needs to be unique 355 | someValidName(), // value doesn't matter here 356 | someManeColor(), 357 | someValidHornLength(), 358 | someValidHornDiameter(), 359 | today.minusYears(62)); // this matters 360 | ``` 361 | 362 | See also [Explicit Constants](#explicit-constants) 363 | 364 | ### Test Setup Helper Method 365 | 366 | Create test setup helper methods to avoid duplication of test object setup in a lot of tests. 367 | 368 | ```java 369 | private Unicorn createUnicornBornAt( 370 | LocalDate dateOfBirth) { 371 | return new Unicorn( 372 | randomUUID(), SOME_NAME, SOME_MANE_COLOR, 373 | SOME_HORN_LENGTH, SOME_HORN_DIAMETER, 374 | dateOfBirth); 375 | } 376 | 377 | @Test 378 | void age() { 379 | var gilly = createUnicornBornAt( 380 | today.minusYears(62)); 381 | 382 | assertThat(gilly.age()) 383 | .isEqualTo(62); 384 | } 385 | ``` 386 | 387 | See also [Test Data Builder](#test-data-builder) 388 | 389 | ### Test Data Builder 390 | 391 | Create a builder class that allows to create whatever object is required for the test. 392 | That builder class should contain or use [random data generators](#random-data-generators) or [constants](#explicit-constants) to fill all the fields that are deemed irrelevant for the test at hand. 393 | 394 | ```java 395 | var unicorn = new UnicornTestDataBuilder() 396 | .name("Micha") 397 | .build(); 398 | ``` 399 | 400 | There might be also libraries that spare you the burden of writing these builders yourself, e.g. [Instancio](https://www.instancio.org/). 401 | 402 | See also [Alberto López del Toro on why you should use Test Data Builders](https://betterprogramming.pub/why-you-should-use-test-data-builders-714eb9de20c1) 403 | 404 | ### Verification Method 405 | 406 | Group long asserts that check one logical thing in verification methods. 407 | This reduces the amount of code in the test itself, and the method name makes the intention more obvious. 408 | 409 | ```java 410 | assertThat(isValidUnicorn(response.body())) 411 | .isTrue(); 412 | assertThat(jsonContainsUnicorn(response.body(), unicorn)) 413 | .isTrue(); 414 | ``` 415 | 416 | AssertJ also allows to use your own [Conditions](https://assertj.github.io/doc/#assertj-core-conditions) and [Custom Assertions](https://assertj.github.io/doc/#assertj-core-custom-assertions), which can make the verification code even more elegant. 417 | 418 | ```java 419 | UnicornAssert.assertThat(unicorn)) 420 | .isValid() 421 | .isOlderThan(62); 422 | ``` 423 | -------------------------------------------------------------------------------- /structure.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | UnicornControllerReadUnicornWriteUnicornUnicornServiceUnicornUnicornDtoUnicornEntityUnicornRepositoryUnicornStoreAdapterUnicornStoreadapter.driving.httpadapter.driven.dbapplication 527 | --------------------------------------------------------------------------------