├── .gitignore ├── Automatic tests: You won't find it in a book.pdf ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── pl │ └── jm │ ├── DemoApplication.java │ ├── calc │ ├── CalcApi.java │ ├── CalcController.java │ ├── CalcEntity.java │ ├── CalcRepository.java │ ├── CalcService.java │ └── CalcValidator.java │ ├── infrastructure │ └── ModuleApi.java │ └── user │ └── UserApi.java └── test └── java └── pl └── jm ├── InMemoryRepository.java └── calc ├── CalcApiTest.java ├── CalcEntityBuilder.java ├── CalcIntegrationTest.java ├── CalcTestRepository.java └── CalcValidatorTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/** 2 | out/ 3 | 4 | *.class 5 | 6 | .gradle 7 | /build/ 8 | 9 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 10 | !gradle-wrapper.jar 11 | -------------------------------------------------------------------------------- /Automatic tests: You won't find it in a book.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yacekmm/testingDemo/fc2ef30f7ef3df6b14437045e95def7c5e9ac1d5/Automatic tests: You won't find it in a book.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Module unit tests demo 2 | 3 | Simple, basic, yet complete example of the ide of unit and integration tests of modularized system. 4 | 5 | # What is it about? 6 | 7 | This is a part of live coding session of the lecture. 8 | 9 | Slides you can find in the `Automatic tests: You won't find it in a book.pdf` file. 10 | 11 | Session recording is here: https://www.youtube.com/watch?v=_7vfW3DpZvU 12 | 13 | # How to navigate branches 14 | 15 | Watch footers in pdf file with presentation slides. Sometimes the branch name appears in the footer. This is the branch you can checkout to see how the problem mentioned on slide reflects in the source code. 16 | 17 | ## Branch naming 18 | Branch naming schema is as follows: `//`, where: 19 | * `` is the order number of the exercise 20 | * `` is the description what this example is about 21 | * `` represents if this is the beginning of the implementation (`start`) or is it fully implemented example (`done`) 22 | 23 | # How to Run 24 | To run the project use: 25 | `./gradlew bootRun` 26 | 27 | However more important here are tests which can be started with a command: 28 | `./gradlew test` -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'idea' 4 | id 'io.franzbecker.gradle-lombok' version '2.1' 5 | id 'org.springframework.boot' version '2.1.3.RELEASE' 6 | } 7 | 8 | apply plugin: 'io.spring.dependency-management' 9 | 10 | lombok { 11 | version = "1.18.6" 12 | sha256 = "" 13 | } 14 | 15 | group 'pl.jm' 16 | version '1.0-SNAPSHOT' 17 | 18 | sourceCompatibility = 10 19 | 20 | repositories { 21 | mavenCentral() 22 | } 23 | 24 | dependencies { 25 | compile "org.springframework.boot:spring-boot-starter-web" 26 | compile "org.springframework.boot:spring-boot-starter-data-jpa" 27 | runtimeOnly 'com.h2database:h2' 28 | 29 | compileOnly 'org.projectlombok:lombok:1.18.6' 30 | annotationProcessor 'org.projectlombok:lombok:1.18.6' 31 | 32 | testCompile 'org.springframework.boot:spring-boot-starter-test' 33 | testCompile 'io.rest-assured:rest-assured:3.0.0' 34 | } 35 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yacekmm/testingDemo/fc2ef30f7ef3df6b14437045e95def7c5e9ac1d5/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'testing' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/pl/jm/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package pl.jm; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/pl/jm/calc/CalcApi.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import lombok.AllArgsConstructor; 4 | import pl.jm.infrastructure.ModuleApi; 5 | 6 | @ModuleApi 7 | @AllArgsConstructor 8 | public class CalcApi { 9 | 10 | private final CalcService calcService; 11 | 12 | public int calculateRating(int age) { 13 | return calcService.calculateRating(age); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/pl/jm/calc/CalcController.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import lombok.AllArgsConstructor; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.PathVariable; 6 | import org.springframework.web.bind.annotation.PostMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import java.util.Map; 10 | 11 | @RestController 12 | @AllArgsConstructor 13 | public class CalcController { 14 | 15 | private CalcApi calcApi; 16 | 17 | @PostMapping("/calc/{age}") 18 | public ResponseEntity> calculateRating( 19 | @PathVariable("age") int age) { 20 | 21 | return ResponseEntity 22 | .ok(Map.of("result", calcApi.calculateRating(age))); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/pl/jm/calc/CalcEntity.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.Id; 10 | import javax.persistence.Table; 11 | import java.util.UUID; 12 | 13 | @Entity 14 | @Table(name = "calculations") 15 | @AllArgsConstructor 16 | @NoArgsConstructor 17 | @Getter 18 | class CalcEntity { 19 | 20 | @Id 21 | @Column(updatable = false, nullable = false, name = "id") 22 | private UUID id; 23 | 24 | @Column(name = "age") 25 | private Integer age; 26 | 27 | @Column(name = "result") 28 | private Integer result; 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/pl/jm/calc/CalcRepository.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | import java.util.UUID; 6 | 7 | interface CalcRepository extends CrudRepository { 8 | 9 | // Collection findRejectedCalcs(UUID userId); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/pl/jm/calc/CalcService.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import lombok.AllArgsConstructor; 4 | import org.springframework.stereotype.Service; 5 | import pl.jm.user.UserApi; 6 | 7 | import java.util.UUID; 8 | 9 | @Service 10 | @AllArgsConstructor 11 | class CalcService { 12 | 13 | private CalcValidator calcValidator; 14 | private UserApi userApi; 15 | private CalcRepository calcRepository; 16 | 17 | int calculateRating(int age) { 18 | 19 | int rating; 20 | 21 | if (calcValidator.ageIsValid(age) 22 | && userApi.verifyUser(age)) { 23 | rating = age * 2; 24 | } else { 25 | rating = 0; 26 | } 27 | 28 | calcRepository.save(new CalcEntity(UUID.randomUUID(), age, rating)); 29 | return rating; 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/pl/jm/calc/CalcValidator.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | @Component 6 | class CalcValidator { 7 | 8 | boolean ageIsValid(int age){ 9 | return age >= 18; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/pl/jm/infrastructure/ModuleApi.java: -------------------------------------------------------------------------------- 1 | package pl.jm.infrastructure; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | @Target({ElementType.TYPE}) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | 13 | @Component 14 | public @interface ModuleApi { 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/pl/jm/user/UserApi.java: -------------------------------------------------------------------------------- 1 | package pl.jm.user; 2 | 3 | import pl.jm.infrastructure.ModuleApi; 4 | 5 | @ModuleApi 6 | public class UserApi { 7 | 8 | public boolean verifyUser(int age) { 9 | //put your very complex logic here 10 | return true; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/pl/jm/InMemoryRepository.java: -------------------------------------------------------------------------------- 1 | package pl.jm; 2 | 3 | import lombok.SneakyThrows; 4 | import org.apache.commons.lang3.reflect.MethodUtils; 5 | import org.springframework.data.repository.CrudRepository; 6 | 7 | import java.io.Serializable; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Optional; 11 | 12 | public class InMemoryRepository implements CrudRepository { 13 | 14 | protected Map database = new HashMap<>(); 15 | 16 | @Override 17 | public S save(S entity) { 18 | 19 | final ID id = (ID) getId(entity); 20 | 21 | if (findById(id).isPresent()) { 22 | throw new IllegalStateException("inserting duplicating entry with id: " + id); 23 | } 24 | 25 | database.put(id, entity); 26 | return entity; 27 | } 28 | 29 | @Override 30 | public Iterable findAll() { 31 | return database.values(); 32 | } 33 | 34 | @Override 35 | public Optional findById(ID id) { 36 | return Optional.ofNullable(database.get(id)); 37 | } 38 | 39 | @Override 40 | public Iterable saveAll(Iterable entities) { 41 | throw new RuntimeException("Not Implemented"); 42 | } 43 | 44 | @Override 45 | public boolean existsById(ID id) { 46 | throw new RuntimeException("Not Implemented"); 47 | } 48 | 49 | @Override 50 | public Iterable findAllById(Iterable ids) { 51 | throw new RuntimeException("Not Implemented"); 52 | } 53 | 54 | @Override 55 | public long count() { 56 | throw new RuntimeException("Not Implemented"); 57 | } 58 | 59 | @Override 60 | public void deleteById(ID id) { 61 | throw new RuntimeException("Not Implemented"); 62 | } 63 | 64 | @Override 65 | public void delete(T entity) { 66 | throw new RuntimeException("Not Implemented"); 67 | } 68 | 69 | @Override 70 | public void deleteAll(Iterable entities) { 71 | throw new RuntimeException("Not Implemented"); 72 | } 73 | 74 | @Override 75 | public void deleteAll() { 76 | throw new RuntimeException("Not Implemented"); 77 | } 78 | 79 | @SneakyThrows 80 | private static Object getId(Object t) { 81 | return MethodUtils.invokeMethod(t, "getId"); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/test/java/pl/jm/calc/CalcApiTest.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import pl.jm.user.UserApi; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | import static org.mockito.ArgumentMatchers.anyInt; 9 | import static org.mockito.BDDMockito.given; 10 | import static org.mockito.Mockito.mock; 11 | 12 | public class CalcApiTest { 13 | 14 | private CalcApi calcApi; 15 | private CalcRepository calcRepository; 16 | private UserApi userApi; 17 | private CalcEntityBuilder calcEntityBuilder; 18 | 19 | @Before 20 | public void setUp() { 21 | calcRepository = new CalcTestRepository(); 22 | userApi = mock(UserApi.class); 23 | 24 | calcApi = new CalcApi( 25 | new CalcService(new CalcValidator(), userApi, calcRepository) 26 | ); 27 | 28 | calcEntityBuilder = CalcEntityBuilder.aCalcEntity(calcRepository); 29 | 30 | given(userApi.verifyUser(anyInt())).willReturn(true); 31 | } 32 | 33 | @Test 34 | public void calculate_returnsRating_forAdult() { 35 | //when 36 | int result = calcApi.calculateRating(22); 37 | 38 | //then 39 | assertThat(result).isEqualTo(44); 40 | } 41 | 42 | @Test 43 | public void calculate_savesRating() { 44 | //when 45 | int result = calcApi.calculateRating(22); 46 | 47 | //then 48 | assertThat(result).isEqualTo(44); 49 | assertThat(calcRepository.findAll()).hasSize(1); 50 | } 51 | 52 | @Test 53 | public void calculate_returnsZero_forNotAdult() { 54 | //when 55 | int result = calcApi.calculateRating(2); 56 | 57 | //then 58 | assertThat(result).isEqualTo(0); 59 | } 60 | 61 | @Test 62 | public void calculate_returnsZero_forNotPermittedAdultUser() { 63 | //given 64 | given(userApi.verifyUser(anyInt())).willReturn(false); 65 | 66 | //when 67 | int result = calcApi.calculateRating(23); 68 | 69 | //then 70 | assertThat(result).isEqualTo(0); 71 | } 72 | 73 | @Test 74 | public void demo_storesCalcInDb(){ 75 | //when 76 | CalcEntity calcEntity = calcEntityBuilder.inDb(); 77 | 78 | //then 79 | assertThat(calcRepository.findById(calcEntity.getId())).isNotEmpty(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/test/java/pl/jm/calc/CalcEntityBuilder.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import java.util.UUID; 4 | 5 | public final class CalcEntityBuilder { 6 | 7 | private UUID id = UUID.randomUUID(); 8 | private Integer age = 23; 9 | private Integer result = 46; 10 | 11 | private final CalcRepository calcRepository; 12 | 13 | private CalcEntityBuilder(CalcRepository calcRepository) { 14 | this.calcRepository = calcRepository; 15 | } 16 | 17 | public static CalcEntityBuilder aCalcEntity(CalcRepository calcRepository) { 18 | return new CalcEntityBuilder(calcRepository); 19 | } 20 | 21 | public CalcEntity build() { 22 | return new CalcEntity(id, age, result); 23 | } 24 | 25 | public CalcEntity inDb(){ 26 | return calcRepository.save(build()); 27 | } 28 | 29 | public CalcEntityBuilder withId(UUID id) { 30 | this.id = id; 31 | return this; 32 | } 33 | 34 | public CalcEntityBuilder withAge(Integer age) { 35 | this.age = age; 36 | return this; 37 | } 38 | 39 | public CalcEntityBuilder withResult(Integer result) { 40 | this.result = result; 41 | return this; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/pl/jm/calc/CalcIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import io.restassured.RestAssured; 4 | import io.restassured.response.Response; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import static org.apache.http.HttpStatus.SC_OK; 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; 15 | import static pl.jm.calc.CalcEntityBuilder.aCalcEntity; 16 | 17 | @RunWith(SpringRunner.class) 18 | @SpringBootTest(webEnvironment = DEFINED_PORT, properties = "server.port=9090") 19 | public class CalcIntegrationTest { 20 | 21 | @Autowired 22 | private CalcRepository calcRepository; 23 | 24 | private CalcEntityBuilder calcEntityBuilder; 25 | 26 | @Before 27 | public void setUp() { 28 | calcEntityBuilder = aCalcEntity(calcRepository); 29 | calcRepository.deleteAll(); 30 | } 31 | 32 | @Test 33 | public void calculate_returnsRating_forAdult() { 34 | //when 35 | Response response = RestAssured.post("http://localhost:9090/calc/22"); 36 | 37 | //then 38 | assertThat(response.statusCode()).isEqualTo(SC_OK); 39 | assertThat(response.jsonPath().getInt("result")).isEqualTo(44); 40 | assertThat(calcRepository.findAll()).hasSize(1); 41 | } 42 | 43 | @Test 44 | public void demo_storesCalcInDb(){ 45 | //when 46 | CalcEntity calcEntity = calcEntityBuilder.inDb(); 47 | 48 | //then 49 | assertThat(calcRepository.findById(calcEntity.getId())).isNotEmpty(); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/pl/jm/calc/CalcTestRepository.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import pl.jm.InMemoryRepository; 4 | 5 | import java.util.UUID; 6 | 7 | class CalcTestRepository 8 | extends InMemoryRepository 9 | implements CalcRepository { 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/pl/jm/calc/CalcValidatorTest.java: -------------------------------------------------------------------------------- 1 | package pl.jm.calc; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.assertj.core.api.Assertions.assertThat; 7 | 8 | public class CalcValidatorTest { 9 | 10 | CalcValidator calcValidator; 11 | 12 | @Before 13 | public void setUp() { 14 | calcValidator = new CalcValidator(); 15 | } 16 | 17 | @Test 18 | public void ageValidation_returnsValid() { 19 | 20 | assertThat(calcValidator.ageIsValid(18)).isTrue(); 21 | assertThat(calcValidator.ageIsValid(33)).isTrue(); 22 | assertThat(calcValidator.ageIsValid(Integer.MAX_VALUE)).isTrue(); 23 | } 24 | 25 | @Test 26 | public void ageValidation_returnsNotValid() { 27 | 28 | assertThat(calcValidator.ageIsValid(17)).isFalse(); 29 | assertThat(calcValidator.ageIsValid(0)).isFalse(); 30 | assertThat(calcValidator.ageIsValid(Integer.MIN_VALUE)).isFalse(); 31 | } 32 | } --------------------------------------------------------------------------------