├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── startwithjava │ │ ├── DemoApplication.java │ │ ├── config │ │ └── DemoConfig.java │ │ ├── controller │ │ ├── UserController.java │ │ ├── request │ │ │ └── CreateEmployeeRequest.java │ │ └── response │ │ │ ├── UserListResponse.java │ │ │ └── UserResponse.java │ │ ├── dao │ │ ├── UserDao.java │ │ ├── UserDaoImpl.java │ │ ├── entity │ │ │ ├── AddressEntity.java │ │ │ └── UserEntity.java │ │ └── repository │ │ │ ├── UserRepository.java │ │ │ └── projection │ │ │ └── UserProjection.java │ │ ├── dto │ │ └── User.java │ │ ├── exception │ │ ├── APIException.java │ │ ├── ApiExceptionHandler.java │ │ └── UserNotFoundException.java │ │ ├── service │ │ ├── UserService.java │ │ ├── UserServiceImpl.java │ │ └── dto │ │ │ └── UserDto.java │ │ └── translator │ │ └── BaseTranslator.java └── resources │ └── application.properties └── test └── java └── com └── startwithjava ├── controller └── UserControllerTest.java ├── dao └── UserDaoImplTest.java └── service └── UserServiceImplTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | .idea/ 3 | *.iml 4 | .gradle/ 5 | .settings/ 6 | .classpath 7 | .project 8 | bin/ 9 | out/ 10 | build/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpringBoot : Unit Testing using Junit 5 and Mockito 2 | This repository focused on Unit testing of a Spring Boot Application. Unit test cases covered for DAOs,Services and Controllers. 3 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '2.0.5.RELEASE' 4 | } 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 | } 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: 'eclipse' 15 | apply plugin: 'org.springframework.boot' 16 | apply plugin: 'io.spring.dependency-management' 17 | repositories { 18 | mavenCentral() 19 | mavenLocal() 20 | } 21 | 22 | dependencies { 23 | compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1' 24 | compile ("com.oracle:ojdbc6:11.2.0") 25 | compileOnly 'org.projectlombok:lombok:1.18.2' 26 | compile group: 'org.modelmapper', name: 'modelmapper', version: '2.3.0' 27 | implementation('org.springframework.boot:spring-boot-starter-web') 28 | implementation('org.springframework.boot:spring-boot-starter-data-jpa') 29 | testImplementation('org.springframework.boot:spring-boot-starter-test') 30 | testCompile('org.junit.jupiter:junit-jupiter-api:5.3.1') 31 | testCompile('org.junit.jupiter:junit-jupiter-params:5.3.1') 32 | testRuntime('org.junit.jupiter:junit-jupiter-engine:5.3.1') 33 | } 34 | 35 | test { 36 | useJUnitPlatform() 37 | testLogging { 38 | events "passed", "skipped", "failed" 39 | } 40 | } 41 | 42 | wrapper { 43 | gradleVersion = '4.8' 44 | } 45 | apply plugin: 'java' 46 | apply plugin: 'eclipse' 47 | 48 | repositories { 49 | mavenCentral() 50 | } 51 | group = 'com.startwithjava' 52 | version = '0.0.1-SNAPSHOT' 53 | sourceCompatibility = 1.8 54 | 55 | test { 56 | useJUnitPlatform() 57 | testLogging { 58 | events "passed", "skipped", "failed" 59 | } 60 | } 61 | 62 | wrapper { 63 | gradleVersion = '4.8' 64 | } 65 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gaurav072/SpringBootJunit5Mockito/043203f258377b0ec0c70438336f4db59640c9b2/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Oct 13 17:38:50 IST 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.8-all.zip 7 | -------------------------------------------------------------------------------- /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 | /* 2 | * This settings file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * In a single project build this file can be empty or even removed. 6 | * 7 | * Detailed information about configuring a multi-project build in Gradle can be found 8 | * in the user guide at https://docs.gradle.org/3.5/userguide/multi_project_builds.html 9 | */ 10 | 11 | /* 12 | // To declare projects as part of a multi-project build use the 'include' method 13 | include 'shared' 14 | include 'api' 15 | include 'services:webservice' 16 | */ 17 | 18 | rootProject.name = 'JunitTestSample' 19 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava; 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 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/config/DemoConfig.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.config; 2 | 3 | import org.modelmapper.ModelMapper; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | @Configuration 8 | public class DemoConfig { 9 | @Bean 10 | public ModelMapper modelMapper(){ 11 | return new ModelMapper(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.controller; 2 | 3 | import java.util.List; 4 | 5 | import com.startwithjava.controller.request.CreateEmployeeRequest; 6 | import com.startwithjava.controller.response.UserResponse; 7 | import com.startwithjava.service.dto.UserDto; 8 | import com.startwithjava.translator.BaseTranslator; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import com.startwithjava.exception.UserNotFoundException; 14 | import com.startwithjava.service.UserService; 15 | 16 | import lombok.AllArgsConstructor; 17 | 18 | import javax.validation.Valid; 19 | 20 | @AllArgsConstructor 21 | @RestController 22 | @RequestMapping("/users/") 23 | public class UserController { 24 | private UserService userService; 25 | private BaseTranslator createUserRequestToUserDtoTranslator; 26 | private BaseTranslator userDtoToUserResponseTranslator; 27 | @GetMapping 28 | public ResponseEntity> findAllUsers(){ 29 | return new ResponseEntity(userDtoToUserResponseTranslator.translate(userService.findAll(),UserResponse.class), HttpStatus.OK); 30 | } 31 | @PostMapping 32 | public ResponseEntity create(@RequestBody @Valid CreateEmployeeRequest user){ 33 | return new ResponseEntity(userService.create(createUserRequestToUserDtoTranslator.translate(user,UserDto.class)), HttpStatus.OK); 34 | } 35 | @GetMapping("{id}") 36 | public ResponseEntity findById(@PathVariable("id") long userId){ 37 | return userService.findById(userId) 38 | .map(user->new ResponseEntity(user,HttpStatus.OK)) 39 | .orElseThrow(()->new UserNotFoundException("User not found")); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/controller/request/CreateEmployeeRequest.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.controller.request; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.GeneratedValue; 7 | import javax.validation.constraints.NotNull; 8 | import java.time.LocalDate; 9 | 10 | @Getter 11 | @Setter 12 | public class CreateEmployeeRequest { 13 | @NotNull 14 | private String name; 15 | @NotNull 16 | private String email; 17 | 18 | @NotNull 19 | private LocalDate joiningDate; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/controller/response/UserListResponse.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.controller.response; 2 | 3 | import java.util.List; 4 | 5 | public class UserListResponse { 6 | List response; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/controller/response/UserResponse.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.controller.response; 2 | 3 | public class UserResponse { 4 | private long id; 5 | private String name; 6 | private String email; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.dao; 2 | 3 | import com.startwithjava.dao.entity.UserEntity; 4 | import com.startwithjava.service.dto.UserDto; 5 | 6 | import java.util.List; 7 | import java.util.Optional; 8 | 9 | public interface UserDao { 10 | List findAll(); 11 | long create(UserDto userDto); 12 | Optional findById(long userId); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/dao/UserDaoImpl.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.dao; 2 | 3 | import com.startwithjava.dao.entity.UserEntity; 4 | import com.startwithjava.dao.repository.UserRepository; 5 | import com.startwithjava.service.dto.UserDto; 6 | import com.startwithjava.translator.BaseTranslator; 7 | import lombok.AllArgsConstructor; 8 | import org.springframework.stereotype.Repository; 9 | 10 | import java.util.List; 11 | import java.util.Optional; 12 | 13 | @AllArgsConstructor 14 | @Repository 15 | public class UserDaoImpl implements UserDao { 16 | private UserRepository userRepository; 17 | private BaseTranslator userEntityTranslator; 18 | 19 | @Override 20 | public List findAll() { 21 | return null; 22 | } 23 | 24 | @Override 25 | public long create(UserDto userDto) { 26 | return userRepository.save(userEntityTranslator.translate(userDto,UserEntity.class)).getId(); 27 | } 28 | 29 | @Override 30 | public Optional findById(long userId) { 31 | return userRepository.getById(userId); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/dao/entity/AddressEntity.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.dao.entity; 2 | 3 | import lombok.AllArgsConstructor; 4 | 5 | import javax.persistence.*; 6 | 7 | @AllArgsConstructor 8 | @Entity 9 | @Table(name = "address") 10 | public class AddressEntity { 11 | @Id 12 | @GeneratedValue(strategy = GenerationType.SEQUENCE) 13 | private long id; 14 | private String city; 15 | private String addressLine1; 16 | private String addressLine2; 17 | @ManyToOne 18 | @JoinColumn(name = "userId") 19 | private UserEntity user; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/dao/entity/UserEntity.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.dao.entity; 2 | 3 | import lombok.*; 4 | 5 | import javax.persistence.*; 6 | import java.util.List; 7 | 8 | 9 | @Getter 10 | @Setter 11 | @NoArgsConstructor 12 | @Entity 13 | @Table(name = "users") 14 | public class UserEntity { 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.SEQUENCE) 17 | private Long id; 18 | private String name; 19 | private String email; 20 | @OneToMany(cascade = CascadeType.ALL,mappedBy = "user") 21 | List addresses; 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/dao/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.dao.repository; 2 | 3 | import com.startwithjava.dao.entity.UserEntity; 4 | import com.startwithjava.service.dto.UserDto; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | 7 | import java.util.Optional; 8 | 9 | public interface UserRepository extends JpaRepository { 10 | Optional getById(long id); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/dao/repository/projection/UserProjection.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.dao.repository.projection; 2 | import org.springframework.beans.factory.annotation.Value; 3 | public interface UserProjection { 4 | @Value("#{target.firstname}") 5 | String getFullName(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/dto/User.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.dto; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | @Getter 9 | @Setter 10 | @AllArgsConstructor 11 | @Builder 12 | public class User { 13 | private long id; 14 | private String name; 15 | private String email; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/exception/APIException.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.exception; 2 | 3 | public class APIException extends RuntimeException{ 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/exception/ApiExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.exception; 2 | import com.fasterxml.jackson.databind.exc.InvalidFormatException; 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.http.converter.HttpMessageNotReadableException; 6 | import org.springframework.web.bind.MethodArgumentNotValidException; 7 | import org.springframework.web.bind.annotation.ControllerAdvice; 8 | import org.springframework.web.bind.annotation.ExceptionHandler; 9 | 10 | import java.time.format.DateTimeParseException; 11 | 12 | @ControllerAdvice 13 | public class ApiExceptionHandler { 14 | @ExceptionHandler(Exception.class) 15 | public ResponseEntity handlerGenericError(Exception ex){ 16 | ex.printStackTrace(); 17 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); 18 | } 19 | @ExceptionHandler(UserNotFoundException.class) 20 | public ResponseEntity handlerBadRequest(UserNotFoundException ex){ 21 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); 22 | } 23 | @ExceptionHandler(MethodArgumentNotValidException.class) 24 | public ResponseEntity handlerBadInputs(MethodArgumentNotValidException ex){ 25 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); 26 | } 27 | 28 | @ExceptionHandler(HttpMessageNotReadableException.class) 29 | public ResponseEntity handleInvalidFormatException(HttpMessageNotReadableException ex){ 30 | return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/exception/UserNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.exception; 2 | 3 | public class UserNotFoundException extends RuntimeException { 4 | public UserNotFoundException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.service; 2 | 3 | import com.startwithjava.dto.User; 4 | import com.startwithjava.service.dto.UserDto; 5 | 6 | import java.util.List; 7 | import java.util.Optional; 8 | 9 | public interface UserService { 10 | List findAll(); 11 | long create(UserDto user); 12 | 13 | Optional findById(long userId); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.service; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.springframework.stereotype.Service; 7 | 8 | import com.startwithjava.dto.User; 9 | import com.startwithjava.dao.UserDao; 10 | import com.startwithjava.service.dto.UserDto; 11 | import com.startwithjava.translator.BaseTranslator; 12 | 13 | import lombok.AllArgsConstructor; 14 | 15 | @AllArgsConstructor 16 | @Service 17 | public class UserServiceImpl implements UserService { 18 | private UserDao userDao; 19 | private BaseTranslator userDtoTranslator; 20 | public List findAll(){ 21 | return userDao.findAll(); 22 | } 23 | 24 | @Override 25 | public long create(UserDto user) { 26 | return userDao.create(user); 27 | } 28 | 29 | @Override 30 | public Optional findById(long userId) { 31 | return userDao.findById(userId); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/service/dto/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.service.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | @Getter 8 | @Setter 9 | public class UserDto { 10 | private long id; 11 | private String name; 12 | private String email; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/startwithjava/translator/BaseTranslator.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.translator; 2 | 3 | import lombok.AllArgsConstructor; 4 | import org.modelmapper.ModelMapper; 5 | import org.springframework.stereotype.Component; 6 | import org.springframework.util.Assert; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.Objects; 11 | import java.util.stream.Collectors; 12 | 13 | @AllArgsConstructor 14 | @Component 15 | public class BaseTranslator{ 16 | private ModelMapper mapper; 17 | 18 | public D translate(S source,Class targetType){ 19 | return mapper.map(source,targetType); 20 | } 21 | 22 | public List translate(List source, Class targetType){ 23 | if(Objects.nonNull(source)) { 24 | return source.stream() 25 | .map(element -> translate(element, targetType)) 26 | .collect(Collectors.toList()); 27 | } 28 | return new ArrayList<>(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8089 2 | spring.datasource.url = jdbc:oracle:thin:@localhost:1521:xe 3 | spring.datasource.platform = oracle 4 | spring.datasource.username = gaurav 5 | spring.datasource.password = gaurav@123 6 | spring.datasource.driverClassName= oracle.jdbc.driver.OracleDriver 7 | spring.jpa.show-sql=true 8 | spring.jpa.hibernate.ddl-auto=update -------------------------------------------------------------------------------- /src/test/java/com/startwithjava/controller/UserControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.controller; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.startwithjava.controller.request.CreateEmployeeRequest; 5 | import com.startwithjava.controller.response.UserResponse; 6 | import com.startwithjava.service.UserServiceImpl; 7 | import com.startwithjava.service.dto.UserDto; 8 | import com.startwithjava.translator.BaseTranslator; 9 | import org.junit.jupiter.api.DisplayName; 10 | import org.junit.jupiter.api.Test; 11 | import org.junit.jupiter.api.extension.ExtendWith; 12 | import org.mockito.Mockito; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 15 | import org.springframework.boot.test.mock.mockito.MockBean; 16 | import org.springframework.http.MediaType; 17 | import org.springframework.test.context.junit.jupiter.SpringExtension; 18 | import org.springframework.test.web.servlet.MockMvc; 19 | 20 | import java.util.Arrays; 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | import java.util.Optional; 24 | 25 | import static org.mockito.Mockito.*; 26 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 27 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 28 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 29 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 30 | 31 | @ExtendWith(SpringExtension.class) 32 | @WebMvcTest(value = UserController.class, secure = false) 33 | public class UserControllerTest { 34 | @Autowired 35 | private MockMvc mockMvc; 36 | 37 | @MockBean 38 | private UserServiceImpl userService; 39 | 40 | private ObjectMapper objectMapper= new ObjectMapper(); 41 | @MockBean 42 | private BaseTranslator createUserRequestToUserDtoTranslator; 43 | @MockBean 44 | private BaseTranslator userDtoToUserResponseTranslator; 45 | 46 | 47 | @Test 48 | @DisplayName("Test findAll()") 49 | public void findAllUsers_InputsAreValid_ReturnUserList() throws Exception { 50 | when(userService.findAll()).thenReturn(Arrays.asList(new UserDto())); 51 | mockMvc.perform(get("/users/") 52 | .accept(MediaType.APPLICATION_JSON)) 53 | .andExpect(status().isOk()); 54 | 55 | verify(userService,times(1)).findAll(); 56 | } 57 | @Test 58 | @DisplayName("Test findById() with invalid userId") 59 | public void findUserById_WhenIdIsNotPresent_ReturnUserAsResponse() throws Exception { 60 | when(userService.findById(Mockito.anyLong())).thenReturn(Optional.empty()); 61 | mockMvc.perform(get("/users/{id}",1L) 62 | .accept(MediaType.APPLICATION_JSON)) 63 | .andExpect(status().isNotFound()); 64 | verify(userService,times(1)).findById(Mockito.anyLong()); 65 | } 66 | 67 | @Test 68 | @DisplayName("Test findById() with invalid userId") 69 | public void findUserById_WhenIdIsInValid_ReturnUserAsResponse() throws Exception { 70 | when(userService.findById(Mockito.anyLong())).thenReturn(Optional.empty()); 71 | mockMvc.perform(get("/users/{id}","aa") 72 | .accept(MediaType.APPLICATION_JSON)) 73 | .andExpect(status().isInternalServerError()); 74 | } 75 | 76 | @Test 77 | @DisplayName("Test createUser with valid request") 78 | public void createUser_WhenCreateUserRequestIsIsValid_ReturnUserAsResponse() throws Exception { 79 | //Given 80 | CreateEmployeeRequest createEmployeeRequest = new CreateEmployeeRequest(); 81 | createEmployeeRequest.setEmail("abc@mail.com"); 82 | createEmployeeRequest.setName("Gaurav"); 83 | 84 | UserDto userDto = new UserDto(); 85 | userDto.setEmail("abc@mail.com"); 86 | userDto.setName("Gaurav"); 87 | 88 | 89 | when(userService.create(Mockito.any(UserDto.class))).thenReturn(1l); 90 | when(createUserRequestToUserDtoTranslator.translate(Mockito.any(CreateEmployeeRequest.class),eq(UserDto.class))).thenReturn(userDto); 91 | //When 92 | when(userService.findById(Mockito.anyLong())).thenReturn(Optional.empty()); 93 | mockMvc.perform(post("/users/") 94 | .contentType(MediaType.APPLICATION_JSON) 95 | .content(objectMapper.writeValueAsString(createEmployeeRequest)) 96 | .accept(MediaType.APPLICATION_JSON)) 97 | .andDo(print()) 98 | .andExpect(status().isOk()); 99 | 100 | //Then 101 | verify(userService,times(1)).create(Mockito.any(UserDto.class)); 102 | verify(createUserRequestToUserDtoTranslator,times(1)).translate(Mockito.any(CreateEmployeeRequest.class),eq(UserDto.class)); 103 | } 104 | 105 | @Test 106 | @DisplayName("Test createUser with Invalid request") 107 | public void createUser_WhenCreateUserRequestIsInValid_ReturnUserAsResponse() throws Exception { 108 | //Given 109 | CreateEmployeeRequest createEmployeeRequest = new CreateEmployeeRequest(); 110 | 111 | UserDto userDto = new UserDto(); 112 | userDto.setEmail("abc@mail.com"); 113 | userDto.setName("Gaurav"); 114 | 115 | 116 | when(userService.create(Mockito.any(UserDto.class))).thenReturn(1l); 117 | when(createUserRequestToUserDtoTranslator.translate(Mockito.any(CreateEmployeeRequest.class),eq(UserDto.class))).thenReturn(userDto); 118 | //When 119 | when(userService.findById(Mockito.anyLong())).thenReturn(Optional.empty()); 120 | mockMvc.perform(post("/users/") 121 | .contentType(MediaType.APPLICATION_JSON) 122 | .content(objectMapper.writeValueAsString(createEmployeeRequest)) 123 | .accept(MediaType.APPLICATION_JSON)) 124 | .andDo(print()) 125 | .andExpect(status().isBadRequest()); 126 | } 127 | @Test 128 | @DisplayName("Test createUser with Invalid request") 129 | public void createUser_WhenCreateEmployeeRequestBadInput_ReturnBadRequestAsResponse() throws Exception { 130 | //Given 131 | Map createEmployeeRequest = new HashMap<>(); 132 | createEmployeeRequest.put("name","Suman"); 133 | createEmployeeRequest.put("email","suman@mail.com"); 134 | createEmployeeRequest.put("joiningDate","bad-date-str"); 135 | 136 | mockMvc.perform(post("/users/") 137 | .contentType(MediaType.APPLICATION_JSON) 138 | .content(objectMapper.writeValueAsString(createEmployeeRequest )) 139 | .accept(MediaType.APPLICATION_JSON)) 140 | .andDo(print()) 141 | .andExpect(status().isBadRequest()); 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /src/test/java/com/startwithjava/dao/UserDaoImplTest.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.dao; 2 | 3 | import com.startwithjava.dao.entity.UserEntity; 4 | import com.startwithjava.dao.repository.UserRepository; 5 | import com.startwithjava.service.dto.UserDto; 6 | import com.startwithjava.translator.BaseTranslator; 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.Test; 9 | import org.mockito.InjectMocks; 10 | import org.mockito.Mock; 11 | import org.mockito.Mockito; 12 | import org.mockito.MockitoAnnotations; 13 | 14 | import static org.junit.jupiter.api.Assertions.assertFalse; 15 | import static org.junit.jupiter.api.Assertions.assertNotNull; 16 | import static org.mockito.ArgumentMatchers.eq; 17 | import static org.mockito.Mockito.times; 18 | import static org.mockito.Mockito.verify; 19 | import static org.mockito.Mockito.when; 20 | 21 | public class UserDaoImplTest { 22 | @Mock 23 | private UserRepository userRepository; 24 | @Mock 25 | private BaseTranslator userEntityTranslator; 26 | 27 | @InjectMocks 28 | private UserDaoImpl userDao; 29 | 30 | @BeforeEach 31 | public void setUp(){ 32 | MockitoAnnotations.initMocks(this); 33 | } 34 | 35 | @Test 36 | public void createUser_whenUserDataIsValid_ReturnCreatedUserId(){ 37 | //Given 38 | UserEntity userEntity = new UserEntity(); 39 | userEntity.setId(1L); 40 | 41 | UserDto userDto = new UserDto(); 42 | 43 | when(userRepository.save(Mockito.any(UserEntity.class))).thenReturn(userEntity); 44 | when(userEntityTranslator.translate(Mockito.any(UserDto.class),eq(UserEntity.class))).thenReturn(userEntity); 45 | 46 | //When 47 | Long id = userDao.create(userDto); 48 | 49 | //Then 50 | assertNotNull(id); 51 | verify(userRepository,times(1)).save(Mockito.any(UserEntity.class)); 52 | verify(userEntityTranslator,times(1)).translate(Mockito.any(UserDto.class),eq(UserEntity.class)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/startwithjava/service/UserServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.startwithjava.service; 2 | 3 | import com.startwithjava.dao.UserDao; 4 | import com.startwithjava.dto.User; 5 | import com.startwithjava.service.dto.UserDto; 6 | import com.startwithjava.translator.BaseTranslator; 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.Test; 9 | import org.mockito.InjectMocks; 10 | import org.mockito.Mock; 11 | import org.mockito.MockitoAnnotations; 12 | 13 | import java.util.Arrays; 14 | import java.util.List; 15 | 16 | import static org.junit.jupiter.api.Assertions.assertFalse; 17 | import static org.mockito.Mockito.*; 18 | 19 | public class UserServiceImplTest { 20 | @Mock 21 | private UserDao userDao; 22 | @Mock 23 | private BaseTranslator userDtoTranslator; 24 | 25 | @InjectMocks 26 | private UserServiceImpl userService; 27 | 28 | @BeforeEach 29 | public void setUp(){ 30 | MockitoAnnotations.initMocks(this); 31 | } 32 | 33 | @Test 34 | public void findAll_WhenRecordPresent_ReturnList(){ 35 | //Given 36 | when(userDao.findAll()).thenReturn(Arrays.asList(new UserDto())); 37 | //When 38 | List userDtoList= userService.findAll(); 39 | 40 | //Then 41 | assertFalse(userDtoList.isEmpty()); 42 | verify(userDao,times(1)).findAll(); 43 | } 44 | 45 | } 46 | --------------------------------------------------------------------------------