diff --git a/mockito/.mvn/wrapper/MavenWrapperDownloader.java b/mockito/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..b901097 --- /dev/null +++ b/mockito/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/mockito/.mvn/wrapper/maven-wrapper.properties b/mockito/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/mockito/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/mockito/README.md b/mockito/README.md new file mode 100644 index 0000000..921133e --- /dev/null +++ b/mockito/README.md @@ -0,0 +1,4 @@ +# Examples for [Clean Unit Tests With Mockito on reflectoring.io](https://reflectoring.io/clean-unit-tests-with-mockito) + +This repository contains the source code of the article's examples. +It's based on Spring Boot and follows the Clean Architecture (aka Onion Architecture). diff --git a/mockito/mvnw b/mockito/mvnw new file mode 100755 index 0000000..a16b543 --- /dev/null +++ b/mockito/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mockito/mvnw.cmd b/mockito/mvnw.cmd new file mode 100644 index 0000000..8611571 --- /dev/null +++ b/mockito/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/mockito/pom.xml b/mockito/pom.xml new file mode 100644 index 0000000..62b1be7 --- /dev/null +++ b/mockito/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + org.example.silenum.mockito + mockito-examples + 0.0.1-SNAPSHOT + + + + 11 + 11 + + + 2.4.4 + 3.4.6 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + com.h2database + h2 + runtime + + + + + org.springframework.boot + spring-boot-starter-test + + + org.unitils + unitils-core + ${unitils-core.version} + test + + + org.junit.jupiter + junit-jupiter + test + + + + \ No newline at end of file diff --git a/mockito/src/main/java/org/example/silenum/mockito/business/exception/ElementNotFoundException.java b/mockito/src/main/java/org/example/silenum/mockito/business/exception/ElementNotFoundException.java new file mode 100644 index 0000000..59142f4 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/business/exception/ElementNotFoundException.java @@ -0,0 +1,13 @@ +package org.example.silenum.mockito.business.exception; + +public class ElementNotFoundException extends Exception { + + public ElementNotFoundException(String message) { + super(message); + } + + public ElementNotFoundException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/business/service/BaseService.java b/mockito/src/main/java/org/example/silenum/mockito/business/service/BaseService.java new file mode 100644 index 0000000..37b0cd3 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/business/service/BaseService.java @@ -0,0 +1,17 @@ +package org.example.silenum.mockito.business.service; + +import java.util.function.Supplier; + +import org.example.silenum.mockito.domain.entity.BaseDomain; + +public interface BaseService { + + D save(D domain) throws E; + + D find(Long id) throws E; + + void delete(D domain) throws E; + + Supplier createSupplierOnElementNotFound(String message); + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/business/service/CantonService.java b/mockito/src/main/java/org/example/silenum/mockito/business/service/CantonService.java new file mode 100644 index 0000000..4a78af6 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/business/service/CantonService.java @@ -0,0 +1,29 @@ +package org.example.silenum.mockito.business.service; + +import java.util.Set; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.Country; + +public interface CantonService extends BaseService { + + Canton findByAbbreviation(String abbreviation, boolean loadCities) throws ElementNotFoundException; + + default Canton findByAbbreviation(String abbreviation) throws ElementNotFoundException { + return findByAbbreviation(abbreviation, false); + } + + Canton findByName(String name, boolean loadCities) throws ElementNotFoundException; + + default Canton findByName(String name) throws ElementNotFoundException { + return findByName(name, false); + } + + Set findAllByCountry(Country country, boolean loadCities); + + default Set findAllByCountry(Country country) { + return findAllByCountry(country, false); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/business/service/CantonServiceImpl.java b/mockito/src/main/java/org/example/silenum/mockito/business/service/CantonServiceImpl.java new file mode 100644 index 0000000..d054399 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/business/service/CantonServiceImpl.java @@ -0,0 +1,88 @@ +package org.example.silenum.mockito.business.service; + +import java.util.Collections; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CantonRepository; + +public class CantonServiceImpl implements CantonService { + + private static final String EXCEPTION_MESSAGE_TEMPLATE = "Canton with %s does not exist."; + + private final CantonRepository cantonRepository; + private final CityService cityService; + + public CantonServiceImpl( + CantonRepository cantonRepository, + CityService cityService) { + this.cantonRepository = cantonRepository; + this.cityService = cityService; + } + + @Override + public Canton save(Canton canton) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + canton.getId()); + return cantonRepository.save(canton) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + } + + @Override + public Canton find(Long id) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "id " + id); + return cantonRepository.find(id) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + } + + @Override + public void delete(Canton domain) { + cantonRepository.delete(domain); + } + + @Override + public Supplier createSupplierOnElementNotFound(String message) { + return () -> new ElementNotFoundException(message); + } + + @Override + public Canton findByAbbreviation(String abbreviation, boolean loadCities) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "abbreviation " + abbreviation); + Canton canton = cantonRepository.findByAbbreviation(abbreviation) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + return buildCanton(canton, loadCities); + } + + @Override + public Canton findByName(String name, boolean loadCities) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "name " + name); + Canton canton = cantonRepository.findByName(name) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + return buildCanton(canton, loadCities); + } + + @Override + public Set findAllByCountry(Country country, boolean loadCities) { + Set cantons = cantonRepository.findAllByCountry(country); + return cantons.stream() + .map(canton -> Canton.builder().of(canton) + .setCities(!loadCities ? + Collections.emptySet() : + cityService.findAllByCanton(canton)) + .setCountry(country) + .build()) + .collect(Collectors.toSet()); + } + + private Canton buildCanton(Canton canton, boolean loadCities) { + Set cities = !loadCities ? Collections.emptySet() : cityService.findAllByCanton(canton); + return Canton.builder().of(canton) + .setCities(cities) + .build(); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/business/service/CityService.java b/mockito/src/main/java/org/example/silenum/mockito/business/service/CityService.java new file mode 100644 index 0000000..b5bbc0f --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/business/service/CityService.java @@ -0,0 +1,18 @@ +package org.example.silenum.mockito.business.service; + +import java.util.Set; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; + +public interface CityService extends BaseService { + + City findByName(String name) throws ElementNotFoundException; + + Set findAllByCanton(Canton canton); + + Set findAllByCountry(Country country); + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/business/service/CityServiceImpl.java b/mockito/src/main/java/org/example/silenum/mockito/business/service/CityServiceImpl.java new file mode 100644 index 0000000..99f2c92 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/business/service/CityServiceImpl.java @@ -0,0 +1,69 @@ +package org.example.silenum.mockito.business.service; + +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; + +public class CityServiceImpl implements CityService { + + private static final String EXCEPTION_MESSAGE_TEMPLATE = "City with %s does not exist."; + + private final CityRepository cityRepository; + + public CityServiceImpl(CityRepository cityRepository) { + this.cityRepository = cityRepository; + } + + @Override + public City save(City city) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + city.getId()); + return cityRepository.save(city) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + } + + @Override + public City find(Long id) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + id); + return cityRepository.find(id) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + } + + @Override + public void delete(City domain) { + cityRepository.delete(domain); + } + + @Override + public Supplier createSupplierOnElementNotFound(String message) { + return () -> new ElementNotFoundException(message); + } + + @Override + public City findByName(String name) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "name " + name); + return cityRepository.findByName(name) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + } + + @Override + public Set findAllByCanton(Canton canton) { + return cityRepository.findAllByCanton(canton).stream() + .map(city -> City.builder() + .of(city) + .setCanton(canton) + .build()) + .collect(Collectors.toSet()); + } + + @Override + public Set findAllByCountry(Country country) { + return cityRepository.findAllByCountry(country); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/business/service/CountryService.java b/mockito/src/main/java/org/example/silenum/mockito/business/service/CountryService.java new file mode 100644 index 0000000..f06906e --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/business/service/CountryService.java @@ -0,0 +1,38 @@ +package org.example.silenum.mockito.business.service; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Country; + +public interface CountryService extends BaseService { + + Country findById(Long id, boolean loadCantons, boolean loadCities) throws ElementNotFoundException; + + default Country findById(Long id, boolean loadCantons) throws ElementNotFoundException { + return findById(id, loadCantons, false); + } + + default Country findById(Long id) throws ElementNotFoundException { + return findById(id, false, false); + } + + Country findByName(String name, boolean loadCantons, boolean loadCities) throws ElementNotFoundException; + + default Country findByName(String name, boolean loadCantons) throws ElementNotFoundException { + return findByName(name, loadCantons, false); + } + + default Country findByName(String name) throws ElementNotFoundException { + return findByName(name, false, false); + } + + Country findByCode(String code, boolean loadCantons, boolean loadCities) throws ElementNotFoundException; + + default Country findByCode(String code, boolean loadCantons) throws ElementNotFoundException { + return findByCode(code, loadCantons, false); + } + + default Country findByCode(String code) throws ElementNotFoundException { + return findByCode(code, false, false); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/business/service/CountryServiceImpl.java b/mockito/src/main/java/org/example/silenum/mockito/business/service/CountryServiceImpl.java new file mode 100644 index 0000000..d9d22fe --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/business/service/CountryServiceImpl.java @@ -0,0 +1,82 @@ +package org.example.silenum.mockito.business.service; + +import java.util.Collections; +import java.util.Set; +import java.util.function.Supplier; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CountryRepository; + +public class CountryServiceImpl implements CountryService { + + private static final String EXCEPTION_MESSAGE_TEMPLATE = "Country with %s does not exist."; + + private final CountryRepository countryRepository; + private final CantonService cantonService; + + public CountryServiceImpl( + CountryRepository countryRepository, + CantonService cantonService) { + this.countryRepository = countryRepository; + this.cantonService = cantonService; + } + + @Override + public Country save(Country country) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + country.getId()); + return countryRepository.save(country) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + } + + @Override + public Country find(Long id) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + id); + return countryRepository.find(id) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + } + + @Override + public void delete(Country domain) { + countryRepository.delete(domain); + } + + @Override + public Supplier createSupplierOnElementNotFound(String message) { + return () -> new ElementNotFoundException(message); + } + + @Override + public Country findById(Long id, boolean loadCantons, boolean loadCities) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + id); + Country country = countryRepository.find(id).orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + return buildCountry(country, loadCantons, loadCities); + } + + @Override + public Country findByName(String name, boolean loadCantons, boolean loadCities) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "name " + name); + Country country = countryRepository.findByName(name) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + return buildCountry(country, loadCantons, loadCities); + } + + @Override + public Country findByCode(String code, boolean loadCantons, boolean loadCities) throws ElementNotFoundException { + String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "code " + code); + Country country = countryRepository.findByCode(code) + .orElseThrow(createSupplierOnElementNotFound(exceptionMessage)); + return buildCountry(country, loadCantons, loadCities); + } + + private Country buildCountry(Country country, boolean loadCantons, boolean loadCities) { + Set cantons = !loadCantons ? + Collections.emptySet() : + cantonService.findAllByCountry(country, loadCities); + return Country.builder().of(country) + .setCantons(cantons) + .build(); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/domain/entity/BaseDomain.java b/mockito/src/main/java/org/example/silenum/mockito/domain/entity/BaseDomain.java new file mode 100644 index 0000000..58a375d --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/domain/entity/BaseDomain.java @@ -0,0 +1,83 @@ +package org.example.silenum.mockito.domain.entity; + +import java.time.ZonedDateTime; + +/** + * This {@link BaseDomain} defines the common fields of all domain objects. + * Every domain object must extends this {@link BaseDomain} for further processing. + */ +public abstract class BaseDomain { + + private final Long id; + private final Integer version; + private final ZonedDateTime created; + private final ZonedDateTime updated; + + protected BaseDomain(Builder builder) { + id = builder.id; + version = builder.version; + created = builder.created; + updated = builder.updated; + } + + public Long getId() { + return id; + } + + public Integer getVersion() { + return version; + } + + public ZonedDateTime getCreated() { + return created; + } + + public ZonedDateTime getUpdated() { + return updated; + } + + /** + * Abstract Builder Pattern for Inheritance + * + * @param Builder from Subtype + */ + public abstract static class Builder> { + + private Long id; + private Integer version; + private ZonedDateTime created; + private ZonedDateTime updated; + + protected Builder() { + } + + public T id(Long id) { + this.id = id; + return getThis(); + } + + public T version(Integer version) { + this.version = version; + return getThis(); + } + + public T created(ZonedDateTime created) { + this.created = created; + return getThis(); + } + + public T updated(ZonedDateTime updated) { + this.updated = updated; + return getThis(); + } + + /** + * Returns the this-object of the subtype. + * + * @return this-object of subtype + */ + protected abstract T getThis(); + + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/domain/entity/Canton.java b/mockito/src/main/java/org/example/silenum/mockito/domain/entity/Canton.java new file mode 100644 index 0000000..c378ce3 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/domain/entity/Canton.java @@ -0,0 +1,93 @@ +package org.example.silenum.mockito.domain.entity; + +import java.util.Set; + +public class Canton extends BaseDomain { + + private final String name; + private final String abbreviation; + private final Country country; + private final Set cities; + + private Canton(Builder builder) { + super(builder); + this.name = builder.name; + this.abbreviation = builder.abbreviation; + this.country = builder.country; + this.cities = builder.cities; + } + + public static Builder builder() { + return new Builder(); + } + + public String getName() { + return name; + } + + public String getAbbreviation() { + return abbreviation; + } + + public Country getCountry() { + return country; + } + + public Set getCities() { + return cities; + } + + public static class Builder extends BaseDomain.Builder { + + private String name; + private String abbreviation; + private Country country; + private Set cities; + + private Builder() { + } + + @Override + protected Builder getThis() { + return this; + } + + public Builder setName(String name) { + this.name = name; + return this; + } + + public Builder setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + return this; + } + + public Builder setCountry(Country country) { + this.country = country; + return this; + } + + public Builder setCities(Set cities) { + this.cities = cities; + return this; + } + + public Builder of(Canton canton) { + this.id(canton.getId()); + this.version(canton.getVersion()); + this.created(canton.getCreated()); + this.updated(canton.getUpdated()); + this.name = canton.name; + this.abbreviation = canton.abbreviation; + this.country = canton.country; + this.cities = canton.cities; + return this; + } + + public Canton build() { + return new Canton(this); + } + + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/domain/entity/City.java b/mockito/src/main/java/org/example/silenum/mockito/domain/entity/City.java new file mode 100644 index 0000000..ae95846 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/domain/entity/City.java @@ -0,0 +1,65 @@ +package org.example.silenum.mockito.domain.entity; + +public class City extends BaseDomain { + + private final String name; + private final Canton canton; + + private City(Builder builder) { + super(builder); + this.name = builder.name; + this.canton = builder.canton; + } + + public static Builder builder() { + return new Builder(); + } + + public String getName() { + return name; + } + + public Canton getCanton() { + return canton; + } + + public static class Builder extends BaseDomain.Builder { + + private String name; + private Canton canton; + + private Builder() { + } + + @Override + protected Builder getThis() { + return this; + } + + public Builder setName(String name) { + this.name = name; + return this; + } + + public Builder setCanton(Canton canton) { + this.canton = canton; + return this; + } + + public Builder of(City city) { + this.id(city.getId()); + this.version(city.getVersion()); + this.created(city.getCreated()); + this.updated(city.getUpdated()); + this.name = city.name; + this.canton = city.canton; + return this; + } + + public City build() { + return new City(this); + } + + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/domain/entity/Country.java b/mockito/src/main/java/org/example/silenum/mockito/domain/entity/Country.java new file mode 100644 index 0000000..0b0e770 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/domain/entity/Country.java @@ -0,0 +1,80 @@ +package org.example.silenum.mockito.domain.entity; + +import java.util.Set; + +public class Country extends BaseDomain { + + private final String name; + private final String code; + private final Set cantons; + + private Country(Builder builder) { + super(builder); + this.name = builder.name; + this.code = builder.code; + this.cantons = builder.cantons; + } + + public static Builder builder() { + return new Builder(); + } + + public String getName() { + return name; + } + + public String getCode() { + return code; + } + + public Set getCantons() { + return cantons; + } + + public static class Builder extends BaseDomain.Builder { + + private String name; + private String code; + private Set cantons; + + private Builder() { + } + + @Override + protected Builder getThis() { + return this; + } + + public Builder setName(String name) { + this.name = name; + return this; + } + + public Builder setCode(String code) { + this.code = code; + return this; + } + + public Builder setCantons(Set cantons) { + this.cantons = cantons; + return this; + } + + public Builder of(Country country) { + this.id(country.getId()); + this.version(country.getVersion()); + this.created(country.getCreated()); + this.updated(country.getUpdated()); + this.name = country.name; + this.code = country.code; + this.cantons = country.cantons; + return this; + } + + public Country build() { + return new Country(this); + } + + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/domain/repository/BaseDomainRepository.java b/mockito/src/main/java/org/example/silenum/mockito/domain/repository/BaseDomainRepository.java new file mode 100644 index 0000000..8de091a --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/domain/repository/BaseDomainRepository.java @@ -0,0 +1,15 @@ +package org.example.silenum.mockito.domain.repository; + +import java.util.Optional; + +import org.example.silenum.mockito.domain.entity.BaseDomain; + +public interface BaseDomainRepository { + + Optional save(D domain); + + Optional find(Long id); + + void delete(D domain); + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/domain/repository/CantonRepository.java b/mockito/src/main/java/org/example/silenum/mockito/domain/repository/CantonRepository.java new file mode 100644 index 0000000..d95bb45 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/domain/repository/CantonRepository.java @@ -0,0 +1,17 @@ +package org.example.silenum.mockito.domain.repository; + +import java.util.Optional; +import java.util.Set; + +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.Country; + +public interface CantonRepository extends BaseDomainRepository { + + Optional findByAbbreviation(String abbreviation); + + Optional findByName(String name); + + Set findAllByCountry(Country country); + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/domain/repository/CityRepository.java b/mockito/src/main/java/org/example/silenum/mockito/domain/repository/CityRepository.java new file mode 100644 index 0000000..be78573 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/domain/repository/CityRepository.java @@ -0,0 +1,18 @@ +package org.example.silenum.mockito.domain.repository; + +import java.util.Optional; +import java.util.Set; + +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; + +public interface CityRepository extends BaseDomainRepository { + + Optional findByName(String name); + + Set findAllByCanton(Canton canton); + + Set findAllByCountry(Country country); + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/domain/repository/CountryRepository.java b/mockito/src/main/java/org/example/silenum/mockito/domain/repository/CountryRepository.java new file mode 100644 index 0000000..7903e29 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/domain/repository/CountryRepository.java @@ -0,0 +1,13 @@ +package org.example.silenum.mockito.domain.repository; + +import java.util.Optional; + +import org.example.silenum.mockito.domain.entity.Country; + +public interface CountryRepository extends BaseDomainRepository { + + Optional findByName(String name); + + Optional findByCode(String code); + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/Application.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/Application.java new file mode 100644 index 0000000..1f6286e --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/Application.java @@ -0,0 +1,13 @@ +package org.example.silenum.mockito.infrastructure; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/business/ServiceConfiguration.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/business/ServiceConfiguration.java new file mode 100644 index 0000000..3769365 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/business/ServiceConfiguration.java @@ -0,0 +1,37 @@ +package org.example.silenum.mockito.infrastructure.configuration.business; + +import org.example.silenum.mockito.business.service.CantonService; +import org.example.silenum.mockito.business.service.CantonServiceImpl; +import org.example.silenum.mockito.business.service.CityService; +import org.example.silenum.mockito.business.service.CityServiceImpl; +import org.example.silenum.mockito.business.service.CountryService; +import org.example.silenum.mockito.business.service.CountryServiceImpl; +import org.example.silenum.mockito.domain.repository.CantonRepository; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.example.silenum.mockito.domain.repository.CountryRepository; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ServiceConfiguration { + + @Bean + public CityService cityService(CityRepository cityRepository) { + return new CityServiceImpl(cityRepository); + } + + @Bean + public CantonService cantonService( + CantonRepository cantonRepository, + CityService cityService) { + return new CantonServiceImpl(cantonRepository, cityService); + } + + @Bean + public CountryService countryService( + CountryRepository countryRepository, + CantonService cantonService) { + return new CountryServiceImpl(countryRepository, cantonService); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/mapper/MapperConfiguration.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/mapper/MapperConfiguration.java new file mode 100644 index 0000000..7059ed6 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/mapper/MapperConfiguration.java @@ -0,0 +1,27 @@ +package org.example.silenum.mockito.infrastructure.configuration.mapper; + +import org.example.silenum.mockito.infrastructure.mapper.CantonMapper; +import org.example.silenum.mockito.infrastructure.mapper.CityMapper; +import org.example.silenum.mockito.infrastructure.mapper.CountryMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MapperConfiguration { + + @Bean + public CityMapper cityMapper(CantonMapper cantonMapper) { + return new CityMapper(cantonMapper); + } + + @Bean + public CantonMapper cantonMapper(CountryMapper countryMapper) { + return new CantonMapper(countryMapper); + } + + @Bean + public CountryMapper countryMapper() { + return new CountryMapper(); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/persistence/PersistenceConfiguration.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/persistence/PersistenceConfiguration.java new file mode 100644 index 0000000..643b0a9 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/persistence/PersistenceConfiguration.java @@ -0,0 +1,24 @@ +package org.example.silenum.mockito.infrastructure.configuration.persistence; + +import java.time.ZonedDateTime; +import java.util.Optional; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.auditing.DateTimeProvider; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@Configuration +@EnableJpaAuditing(dateTimeProviderRef = "zonedDateTimeProvider") +@EntityScan(basePackages = "org.example.silenum.mockito.infrastructure.database.entity") +@EnableJpaRepositories(basePackages = "org.example.silenum.mockito.infrastructure.database.repository") +public class PersistenceConfiguration { + + @Bean(name = "zonedDateTimeProvider") + public DateTimeProvider dateTimeProvider() { + return () -> Optional.of(ZonedDateTime.now()); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/repository/RepositoryConfiguration.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/repository/RepositoryConfiguration.java new file mode 100644 index 0000000..9c04318 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/configuration/repository/RepositoryConfiguration.java @@ -0,0 +1,42 @@ +package org.example.silenum.mockito.infrastructure.configuration.repository; + +import org.example.silenum.mockito.domain.repository.CantonRepository; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.example.silenum.mockito.domain.repository.CountryRepository; +import org.example.silenum.mockito.infrastructure.database.repository.CantonEntityRepository; +import org.example.silenum.mockito.infrastructure.database.repository.CityEntityRepository; +import org.example.silenum.mockito.infrastructure.database.repository.CountryEntityRepository; +import org.example.silenum.mockito.infrastructure.mapper.CantonMapper; +import org.example.silenum.mockito.infrastructure.mapper.CityMapper; +import org.example.silenum.mockito.infrastructure.mapper.CountryMapper; +import org.example.silenum.mockito.infrastructure.repository.CantonRepositoryImpl; +import org.example.silenum.mockito.infrastructure.repository.CityRepositoryImpl; +import org.example.silenum.mockito.infrastructure.repository.CountryRepositoryImpl; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RepositoryConfiguration { + + @Bean + public CityRepository cityRepository( + CityEntityRepository cityEntityRepository, + CityMapper cityMapper) { + return new CityRepositoryImpl(cityEntityRepository, cityMapper); + } + + @Bean + public CantonRepository cantonRepository( + CantonEntityRepository cantonEntityRepository, + CantonMapper cantonMapper) { + return new CantonRepositoryImpl(cantonEntityRepository, cantonMapper); + } + + @Bean + public CountryRepository countryRepository( + CountryEntityRepository countryEntityRepository, + CountryMapper countryMapper) { + return new CountryRepositoryImpl(countryEntityRepository, countryMapper); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/BaseEntity.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/BaseEntity.java new file mode 100644 index 0000000..fe285b4 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/BaseEntity.java @@ -0,0 +1,90 @@ +package org.example.silenum.mockito.infrastructure.database.entity; + +import java.time.ZonedDateTime; + +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; +import javax.persistence.Version; + +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; + +/** + * This class defines the common fields for each entity to be persisted. + */ +@MappedSuperclass +public abstract class BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Version + private Integer version; + + @CreatedDate + private ZonedDateTime created; + + @LastModifiedDate + private ZonedDateTime updated; + + protected BaseEntity() { + } + + protected BaseEntity(Builder builder) { + this.id = builder.id; + this.version = builder.version; + this.created = builder.created; + this.updated = builder.updated; + } + + public Long getId() { + return id; + } + + public Integer getVersion() { + return version; + } + + public ZonedDateTime getCreated() { + return created; + } + + public ZonedDateTime getUpdated() { + return updated; + } + + public abstract static class Builder> { + + private Long id; + private Integer version; + private ZonedDateTime created; + private ZonedDateTime updated; + + public T id(Long id) { + this.id = id; + return this.getThis(); + } + + public T version(Integer version) { + this.version = version; + return this.getThis(); + } + + public T created(ZonedDateTime created) { + this.created = created; + return this.getThis(); + } + + public T updated(ZonedDateTime updated) { + this.updated = updated; + return this.getThis(); + } + + protected abstract T getThis(); + + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/CantonEntity.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/CantonEntity.java new file mode 100644 index 0000000..13497c4 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/CantonEntity.java @@ -0,0 +1,122 @@ +package org.example.silenum.mockito.infrastructure.database.entity; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.FetchType; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +@Entity +@Table(name = "canton") +@EntityListeners(AuditingEntityListener.class) +public class CantonEntity extends BaseEntity { + + @Column(nullable = false, unique = true) + private String name; + + @Column(nullable = false, unique = true) + private String abbreviation; + + @OneToMany(mappedBy = "canton", cascade = CascadeType.REMOVE) + private Set cities = new HashSet<>(); + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "countryId") + private CountryEntity country; + + public CantonEntity() { + // Default constructor is required for JPA. + } + + private CantonEntity(Builder builder) { + super(builder); + name = builder.name; + abbreviation = builder.abbreviation; + cities = builder.cities; + country = builder.country; + } + + public static Builder builder() { + return new Builder(); + } + + public static Builder builder(CantonEntity copy) { + Builder builder = new Builder(); + builder.id(copy.getId()); + builder.version(copy.getVersion()); + builder.created(copy.getCreated()); + builder.updated(copy.getUpdated()); + builder.name = copy.getName(); + builder.abbreviation = copy.getAbbreviation(); + builder.cities = copy.getCities(); + builder.country = copy.getCountry(); + return builder; + } + + public String getName() { + return name; + } + + public String getAbbreviation() { + return abbreviation; + } + + public Set getCities() { + return cities; + } + + public CountryEntity getCountry() { + return country; + } + + public static final class Builder extends BaseEntity.Builder { + + private String name; + private String abbreviation; + private Set cities; + private CountryEntity country; + + private Builder() { + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder abbreviation(String abbreviation) { + this.abbreviation = abbreviation; + return this; + } + + public Builder cities(Set cities) { + this.cities = cities; + return this; + } + + public Builder country(CountryEntity country) { + this.country = country; + return this; + } + + public CantonEntity build() { + return new CantonEntity(this); + } + + @Override + protected Builder getThis() { + return this; + } + + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/CityEntity.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/CityEntity.java new file mode 100644 index 0000000..8867ffe --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/CityEntity.java @@ -0,0 +1,88 @@ +package org.example.silenum.mockito.infrastructure.database.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.FetchType; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +@Entity +@Table(name = "city") +@EntityListeners(AuditingEntityListener.class) +public class CityEntity extends BaseEntity { + + @Column(nullable = false) + private String name; + + // Note: This is the owning site (child) of the relation canton-city + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "cantonId") + private CantonEntity canton; + + public CityEntity() { + // Default constructor is required for JPA. + } + + private CityEntity(Builder builder) { + super(builder); + name = builder.name; + canton = builder.canton; + } + + public static Builder builder() { + return new Builder(); + } + + public static Builder builder(CityEntity copy) { + Builder builder = new Builder(); + builder.id(copy.getId()); + builder.version(copy.getVersion()); + builder.created(copy.getCreated()); + builder.updated(copy.getUpdated()); + builder.name = copy.getName(); + builder.canton = copy.getCanton(); + return builder; + } + + public String getName() { + return name; + } + + public CantonEntity getCanton() { + return canton; + } + + public static final class Builder extends BaseEntity.Builder { + + private String name; + private CantonEntity canton; + + private Builder() { + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder canton(CantonEntity canton) { + this.canton = canton; + return this; + } + + public CityEntity build() { + return new CityEntity(this); + } + + @Override + protected Builder getThis() { + return this; + } + + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/CountryEntity.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/CountryEntity.java new file mode 100644 index 0000000..a47a5f6 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/entity/CountryEntity.java @@ -0,0 +1,104 @@ +package org.example.silenum.mockito.infrastructure.database.entity; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +@Entity +@Table(name = "country") +@EntityListeners(AuditingEntityListener.class) +public class CountryEntity extends BaseEntity { + + @Column(nullable = false, unique = true) + private String name; + + @Column(nullable = false, unique = true) + private String code; + + // Note: This is the inverse site (parent) of the relation country-canton + @OneToMany(mappedBy = "country", cascade = CascadeType.REMOVE) + private Set cantons = new HashSet<>(); + + public CountryEntity() { + // Default constructor is required for JPA. + } + + private CountryEntity(Builder builder) { + super(builder); + name = builder.name; + code = builder.code; + cantons = builder.cantons; + } + + public static Builder builder() { + return new Builder(); + } + + public static Builder builder(CountryEntity copy) { + Builder builder = new Builder(); + builder.id(copy.getId()); + builder.version(copy.getVersion()); + builder.created(copy.getCreated()); + builder.updated(copy.getUpdated()); + builder.name = copy.getName(); + builder.code = copy.getCode(); + builder.cantons = copy.getCantons(); + return builder; + } + + public String getName() { + return name; + } + + public String getCode() { + return code; + } + + public Set getCantons() { + return cantons; + } + + public static final class Builder extends BaseEntity.Builder { + + private String name; + private String code; + private Set cantons; + + private Builder() { + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder code(String code) { + this.code = code; + return this; + } + + public Builder cantons(Set cantons) { + this.cantons = cantons; + return this; + } + + public CountryEntity build() { + return new CountryEntity(this); + } + + @Override + protected Builder getThis() { + return this; + } + + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/BaseEntityRepository.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/BaseEntityRepository.java new file mode 100644 index 0000000..4449152 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/BaseEntityRepository.java @@ -0,0 +1,12 @@ +package org.example.silenum.mockito.infrastructure.database.repository; + +import org.example.silenum.mockito.infrastructure.database.entity.BaseEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Intermediate repository for {@link BaseEntity} + * It defines {@link Long} as default type for the ID of the {@link BaseEntity} + */ +public interface BaseEntityRepository extends JpaRepository { + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/CantonEntityRepository.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/CantonEntityRepository.java new file mode 100644 index 0000000..8e48bef --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/CantonEntityRepository.java @@ -0,0 +1,18 @@ +package org.example.silenum.mockito.infrastructure.database.repository; + +import java.util.List; +import java.util.Optional; + +import org.example.silenum.mockito.infrastructure.database.entity.CantonEntity; + +public interface CantonEntityRepository extends BaseEntityRepository { + + Optional findByNameIgnoreCase(String name); + + Optional findByAbbreviationIgnoreCase(String abbreviation); + + List findAllByCountryNameIgnoreCase(String countryName); + + List findAllByCountryId(Long countryId); + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/CityEntityRepository.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/CityEntityRepository.java new file mode 100644 index 0000000..e741380 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/CityEntityRepository.java @@ -0,0 +1,16 @@ +package org.example.silenum.mockito.infrastructure.database.repository; + +import java.util.List; +import java.util.Optional; + +import org.example.silenum.mockito.infrastructure.database.entity.CityEntity; + +public interface CityEntityRepository extends BaseEntityRepository { + + Optional findByNameIgnoreCase(String name); + + List findAllByCantonId(Long cantonId); + + List findAllByCanton_Country_Id(Long countryId); + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/CountryEntityRepository.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/CountryEntityRepository.java new file mode 100644 index 0000000..c99dacf --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/database/repository/CountryEntityRepository.java @@ -0,0 +1,13 @@ +package org.example.silenum.mockito.infrastructure.database.repository; + +import java.util.Optional; + +import org.example.silenum.mockito.infrastructure.database.entity.CountryEntity; + +public interface CountryEntityRepository extends BaseEntityRepository { + + Optional findByNameIgnoreCase(String name); + + Optional findByCodeIgnoreCase(String code); + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/CantonMapper.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/CantonMapper.java new file mode 100644 index 0000000..78c616a --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/CantonMapper.java @@ -0,0 +1,41 @@ +package org.example.silenum.mockito.infrastructure.mapper; + +import java.util.Optional; + +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.infrastructure.database.entity.CantonEntity; + +public final class CantonMapper implements Mapper { + + private final CountryMapper countryMapper; + + public CantonMapper(CountryMapper countryMapper) { + this.countryMapper = countryMapper; + } + + @Override + public Optional toDomain(CantonEntity entity) { + return entity == null ? Optional.empty() : Optional.of(Canton.builder() + .id(entity.getId()) + .version(entity.getVersion()) + .created(entity.getCreated()) + .updated(entity.getUpdated()) + .setName(entity.getName()) + .setAbbreviation(entity.getAbbreviation()) + .build()); + } + + @Override + public CantonEntity toEntity(Canton canton) { + return canton == null ? null : CantonEntity.builder() + .id(canton.getId()) + .version(canton.getVersion()) + .created(canton.getCreated()) + .updated(canton.getUpdated()) + .name(canton.getName()) + .abbreviation(canton.getAbbreviation()) + .country(countryMapper.toEntity(canton.getCountry())) + .build(); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/CityMapper.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/CityMapper.java new file mode 100644 index 0000000..ea5690c --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/CityMapper.java @@ -0,0 +1,39 @@ +package org.example.silenum.mockito.infrastructure.mapper; + +import java.util.Optional; + +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.infrastructure.database.entity.CityEntity; + +public final class CityMapper implements Mapper { + + private final CantonMapper cantonMapper; + + public CityMapper(CantonMapper cantonMapper) { + this.cantonMapper = cantonMapper; + } + + @Override + public Optional toDomain(CityEntity entity) { + return entity == null ? Optional.empty() : Optional.of(City.builder() + .id(entity.getId()) + .version(entity.getVersion()) + .created(entity.getCreated()) + .updated(entity.getUpdated()) + .setName(entity.getName()) + .build()); + } + + @Override + public CityEntity toEntity(City city) { + return city == null ? null : CityEntity.builder() + .id(city.getId()) + .version(city.getVersion()) + .created(city.getCreated()) + .updated(city.getUpdated()) + .name(city.getName()) + .canton(cantonMapper.toEntity(city.getCanton())) + .build(); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/CountryMapper.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/CountryMapper.java new file mode 100644 index 0000000..60a81ea --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/CountryMapper.java @@ -0,0 +1,34 @@ +package org.example.silenum.mockito.infrastructure.mapper; + +import java.util.Optional; + +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.infrastructure.database.entity.CountryEntity; + +public final class CountryMapper implements Mapper { + + @Override + public Optional toDomain(CountryEntity entity) { + return entity == null ? Optional.empty() : Optional.of(Country.builder() + .id(entity.getId()) + .version(entity.getVersion()) + .created(entity.getCreated()) + .updated(entity.getUpdated()) + .setName(entity.getName()) + .setCode(entity.getCode()) + .build()); + } + + @Override + public CountryEntity toEntity(Country domain) { + return domain == null ? null : CountryEntity.builder() + .id(domain.getId()) + .version(domain.getVersion()) + .created(domain.getCreated()) + .updated(domain.getUpdated()) + .name(domain.getName()) + .code(domain.getCode()) + .build(); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/Mapper.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/Mapper.java new file mode 100644 index 0000000..9f60090 --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/mapper/Mapper.java @@ -0,0 +1,36 @@ +package org.example.silenum.mockito.infrastructure.mapper; + +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import org.example.silenum.mockito.domain.entity.BaseDomain; +import org.example.silenum.mockito.infrastructure.database.entity.BaseEntity; + +public interface Mapper { + + default Optional toDomain(Optional entity) { + return entity.isEmpty() ? Optional.empty() : toDomain(entity.get()); + } + + Optional toDomain(E entity); + + default Set toDomain(Collection entities) { + return entities == null ? Collections.emptySet() : entities.stream() + .map(this::toDomain) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toSet()); + } + + E toEntity(D domain); + + default Set toEntity(Collection domains) { + return domains == null ? Collections.emptySet() : domains.stream() + .map(this::toEntity) + .collect(Collectors.toSet()); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/repository/CantonRepositoryImpl.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/repository/CantonRepositoryImpl.java new file mode 100644 index 0000000..fd656df --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/repository/CantonRepositoryImpl.java @@ -0,0 +1,63 @@ +package org.example.silenum.mockito.infrastructure.repository; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CantonRepository; +import org.example.silenum.mockito.infrastructure.database.entity.CantonEntity; +import org.example.silenum.mockito.infrastructure.database.repository.CantonEntityRepository; +import org.example.silenum.mockito.infrastructure.mapper.CantonMapper; + +public class CantonRepositoryImpl implements CantonRepository { + + private final CantonEntityRepository cantonEntityRepository; + private final CantonMapper cantonMapper; + + public CantonRepositoryImpl( + CantonEntityRepository cantonEntityRepository, + CantonMapper cantonMapper) { + this.cantonEntityRepository = cantonEntityRepository; + this.cantonMapper = cantonMapper; + } + + @Override + public Optional save(Canton domain) { + CantonEntity cantonEntity = cantonMapper.toEntity(domain); + cantonEntity = cantonEntityRepository.save(cantonEntity); + return cantonMapper.toDomain(cantonEntity); + } + + @Override + public Optional find(Long id) { + Optional cantonEntity = cantonEntityRepository.findById(id); + return cantonMapper.toDomain(cantonEntity); + } + + @Override + public void delete(Canton domain) { + Optional cantonEntity = cantonEntityRepository.findById(domain.getId()); + cantonEntity.ifPresent(cantonEntityRepository::delete); + } + + @Override + public Optional findByAbbreviation(String abbreviation) { + Optional cantonEntity = cantonEntityRepository.findByAbbreviationIgnoreCase(abbreviation); + return cantonMapper.toDomain(cantonEntity); + } + + @Override + public Optional findByName(String name) { + Optional cantonEntity = cantonEntityRepository.findByNameIgnoreCase(name); + return cantonMapper.toDomain(cantonEntity); + } + + @Override + public Set findAllByCountry(Country country) { + List cantonEntities = cantonEntityRepository.findAllByCountryNameIgnoreCase(country.getName()); + return cantonMapper.toDomain(cantonEntities); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/repository/CityRepositoryImpl.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/repository/CityRepositoryImpl.java new file mode 100644 index 0000000..260401c --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/repository/CityRepositoryImpl.java @@ -0,0 +1,64 @@ +package org.example.silenum.mockito.infrastructure.repository; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.example.silenum.mockito.infrastructure.database.entity.CityEntity; +import org.example.silenum.mockito.infrastructure.database.repository.CityEntityRepository; +import org.example.silenum.mockito.infrastructure.mapper.CityMapper; + +public class CityRepositoryImpl implements CityRepository { + + private final CityEntityRepository cityEntityRepository; + private final CityMapper cityMapper; + + public CityRepositoryImpl( + CityEntityRepository cityEntityRepository, + CityMapper cityMapper) { + this.cityEntityRepository = cityEntityRepository; + this.cityMapper = cityMapper; + } + + @Override + public Optional save(City domain) { + CityEntity cityEntity = cityMapper.toEntity(domain); + cityEntity = cityEntityRepository.save(cityEntity); + return cityMapper.toDomain(cityEntity); + } + + @Override + public Optional find(Long id) { + Optional cityEntity = cityEntityRepository.findById(id); + return cityMapper.toDomain(cityEntity); + } + + @Override + public void delete(City domain) { + Optional cantonEntity = cityEntityRepository.findById(domain.getId()); + cantonEntity.ifPresent(cityEntityRepository::delete); + } + + @Override + public Optional findByName(String name) { + Optional cityEntity = cityEntityRepository.findByNameIgnoreCase(name); + return cityMapper.toDomain(cityEntity); + } + + @Override + public Set findAllByCanton(Canton canton) { + List cityEntities = cityEntityRepository.findAllByCantonId(canton.getId()); + return cityMapper.toDomain(cityEntities); + } + + @Override + public Set findAllByCountry(Country country) { + List cities = cityEntityRepository.findAllByCanton_Country_Id(country.getId()); + return cityMapper.toDomain(cities); + } + +} diff --git a/mockito/src/main/java/org/example/silenum/mockito/infrastructure/repository/CountryRepositoryImpl.java b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/repository/CountryRepositoryImpl.java new file mode 100644 index 0000000..3b9924d --- /dev/null +++ b/mockito/src/main/java/org/example/silenum/mockito/infrastructure/repository/CountryRepositoryImpl.java @@ -0,0 +1,54 @@ +package org.example.silenum.mockito.infrastructure.repository; + +import java.util.Optional; + +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CountryRepository; +import org.example.silenum.mockito.infrastructure.database.entity.CountryEntity; +import org.example.silenum.mockito.infrastructure.database.repository.CountryEntityRepository; +import org.example.silenum.mockito.infrastructure.mapper.CountryMapper; + +public class CountryRepositoryImpl implements CountryRepository { + + private final CountryEntityRepository countryEntityRepository; + private final CountryMapper countryMapper; + + public CountryRepositoryImpl( + CountryEntityRepository countryEntityRepository, + CountryMapper countryMapper) { + this.countryEntityRepository = countryEntityRepository; + this.countryMapper = countryMapper; + } + + @Override + public Optional save(Country domain) { + CountryEntity countryEntity = countryMapper.toEntity(domain); + countryEntity = countryEntityRepository.save(countryEntity); + return countryMapper.toDomain(countryEntity); + } + + @Override + public Optional find(Long id) { + Optional countryEntity = countryEntityRepository.findById(id); + return countryMapper.toDomain(countryEntity); + } + + @Override + public void delete(Country domain) { + Optional countryEntity = countryEntityRepository.findById(domain.getId()); + countryEntity.ifPresent(countryEntityRepository::delete); + } + + @Override + public Optional findByName(String name) { + Optional countryEntity = countryEntityRepository.findByNameIgnoreCase(name); + return countryMapper.toDomain(countryEntity); + } + + @Override + public Optional findByCode(String code) { + Optional countryEntity = countryEntityRepository.findByCodeIgnoreCase(code); + return countryMapper.toDomain(countryEntity); + } + +} diff --git a/mockito/src/main/resources/application.yml b/mockito/src/main/resources/application.yml new file mode 100644 index 0000000..0417393 --- /dev/null +++ b/mockito/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + datasource: + username: sa + password: + url: jdbc:h2:mem:world + + jpa: + database-platform: org.hibernate.dialect.H2Dialect + h2: + console: + enabled: true \ No newline at end of file diff --git a/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTest.java b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTest.java new file mode 100644 index 0000000..f2b5c60 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTest.java @@ -0,0 +1,131 @@ +package org.example.silenum.mockito.business.service; + +import java.time.ZonedDateTime; +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.unitils.reflectionassert.ReflectionAssert; + +class CityServiceImplTest { + + // System under Test (SuT) + private CityService cityService; + + // Mocks + private CityRepository cityRepository; + + @BeforeEach + void setUp() { + cityRepository = Mockito.mock(CityRepository.class); + cityService = new CityServiceImpl(cityRepository); + } + + @Test + void save() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.save(expected)) + .thenReturn(Optional.of(expected)); + City actual = cityService.save(expected); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void find() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.find(expected.getId())) + .thenReturn(Optional.of(expected)); + City actual = cityService.find(expected.getId()); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void delete() throws ElementNotFoundException { + City expected = createCity(); + cityService.delete(expected); + Mockito.verify(cityRepository).delete(expected); + } + + @Test + void findByName() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.findByName(expected.getName())) + .thenReturn(Optional.of(expected)); + City actual = cityService.findByName(expected.getName()); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void findByNameThrowsExceptionIfCityNameContainsIllegalCharacter() { + String cityName = "C!tyN@me"; + Mockito.when(cityRepository.findByName(cityName)) + .thenThrow(IllegalArgumentException.class); + Assertions.assertThrows(IllegalArgumentException.class, () -> cityService.findByName(cityName)); + } + + @Test + void findAllByCanton() { + City city = createCity(); + Canton canton = city.getCanton(); + Mockito.when(cityRepository.findAllByCanton(canton)) + .thenReturn(Collections.singleton(city)); + Set expected = Set.of(city); + Set actual = cityService.findAllByCanton(canton); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void findAllByCountry() { + City city = createCity(); + Country country = city.getCanton().getCountry(); + Mockito.when(cityRepository.findAllByCountry(country)) + .thenReturn(Collections.singleton(city)); + Set expected = Set.of(city); + Set actual = cityService.findAllByCountry(country); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .setCanton(createCanton()) + .build(); + } + + private Canton createCanton() { + return Canton.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Canton" + System.currentTimeMillis()) + .setAbbreviation("SC-" + System.currentTimeMillis()) + .setCountry(createCountry()) + .build(); + } + + private Country createCountry() { + return Country.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Switzerland") + .build(); + } + +} \ No newline at end of file diff --git a/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoAnnotationStyle.java b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoAnnotationStyle.java new file mode 100644 index 0000000..7dc59f4 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoAnnotationStyle.java @@ -0,0 +1,125 @@ +package org.example.silenum.mockito.business.service; + +import java.time.ZonedDateTime; +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.unitils.reflectionassert.ReflectionAssert; + +class CityServiceImplTestMockitoAnnotationStyle { + + // System under Test (SuT) + private CityService cityService; + + // Mocks + @Mock + private CityRepository cityRepository; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + cityService = new CityServiceImpl(cityRepository); + } + + @Test + void save() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.save(expected)) + .thenReturn(Optional.of(expected)); + City actual = cityService.save(expected); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void find() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.find(expected.getId())) + .thenReturn(Optional.of(expected)); + City actual = cityService.find(expected.getId()); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void delete() throws ElementNotFoundException { + City expected = createCity(); + cityService.delete(expected); + Mockito.verify(cityRepository).delete(expected); + } + + @Test + void findByName() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.findByName(expected.getName())) + .thenReturn(Optional.of(expected)); + City actual = cityService.findByName(expected.getName()); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void findAllByCanton() { + City city = createCity(); + Canton canton = city.getCanton(); + Mockito.when(cityRepository.findAllByCanton(canton)) + .thenReturn(Collections.singleton(city)); + Set expected = Set.of(city); + Set actual = cityService.findAllByCanton(canton); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void findAllByCountry() { + City city = createCity(); + Country country = city.getCanton().getCountry(); + Mockito.when(cityRepository.findAllByCountry(country)) + .thenReturn(Collections.singleton(city)); + Set expected = Set.of(city); + Set actual = cityService.findAllByCountry(country); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .setCanton(createCanton()) + .build(); + } + + private Canton createCanton() { + return Canton.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Canton" + System.currentTimeMillis()) + .setAbbreviation("SC-" + System.currentTimeMillis()) + .setCountry(createCountry()) + .build(); + } + + private Country createCountry() { + return Country.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Switzerland") + .build(); + } + +} \ No newline at end of file diff --git a/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoDonts.java b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoDonts.java new file mode 100644 index 0000000..8f71bf2 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoDonts.java @@ -0,0 +1,114 @@ +package org.example.silenum.mockito.business.service; + +import java.time.ZonedDateTime; +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.unitils.reflectionassert.ReflectionAssert; + +class CityServiceImplTestMockitoDonts { + + // System under Test (SuT) + private CityService cityService; + + // Mocks + private CityRepository cityRepository; + + // Helper + private City expected; + + @BeforeEach + void setUp() { + expected = createCity(); + cityRepository = Mockito.mock(CityRepository.class); + cityService = new CityServiceImpl(cityRepository); + + Mockito.when(cityRepository.save(expected)) + .thenReturn(Optional.of(expected)); + Mockito.when(cityRepository.find(expected.getId())) + .thenReturn(Optional.of(expected)); + Mockito.when(cityRepository.findByName(expected.getName())) + .thenReturn(Optional.of(expected)); + Mockito.when(cityRepository.findAllByCanton(expected.getCanton())) + .thenReturn(Collections.singleton(expected)); + Mockito.when(cityRepository.findAllByCountry(expected.getCanton().getCountry())) + .thenReturn(Collections.singleton(expected)); + } + + @Test + void save() throws ElementNotFoundException { + ReflectionAssert.assertReflectionEquals(expected, cityService.save(expected)); + } + + @Test + void find() throws ElementNotFoundException { + ReflectionAssert.assertReflectionEquals(expected, cityService.find(expected.getId())); + } + + @Test + void delete() throws ElementNotFoundException { + cityService.delete(expected); + Mockito.verify(cityRepository).delete(expected); + } + + @Test + void findByName() throws ElementNotFoundException { + ReflectionAssert.assertReflectionEquals(expected, cityService.findByName(expected.getName())); + } + + @Test + void findAllByCanton() { + Set expectedSet = Set.of(expected); + ReflectionAssert.assertReflectionEquals(expectedSet, cityService.findAllByCanton(expected.getCanton())); + } + + @Test + void findAllByCountry() { + Set expectedSet = Set.of(expected); + ReflectionAssert.assertReflectionEquals(expectedSet, cityService.findAllByCountry(expected.getCanton().getCountry())); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .setCanton(createCanton()) + .build(); + } + + private Canton createCanton() { + return Canton.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Canton" + System.currentTimeMillis()) + .setAbbreviation("SC-" + System.currentTimeMillis()) + .setCountry(createCountry()) + .build(); + } + + private Country createCountry() { + return Country.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Switzerland") + .build(); + } + +} \ No newline at end of file diff --git a/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoJUnitExtensionStyle.java b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoJUnitExtensionStyle.java new file mode 100644 index 0000000..5231bcb --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoJUnitExtensionStyle.java @@ -0,0 +1,127 @@ +package org.example.silenum.mockito.business.service; + +import java.time.ZonedDateTime; +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.unitils.reflectionassert.ReflectionAssert; + +@ExtendWith(MockitoExtension.class) +class CityServiceImplTestMockitoJUnitExtensionStyle { + + // System under Test (SuT) + private CityService cityService; + + // Mocks + @Mock + private CityRepository cityRepository; + + @BeforeEach + void setUp() { + cityService = new CityServiceImpl(cityRepository); + } + + @Test + void save() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.save(expected)) + .thenReturn(Optional.of(expected)); + City actual = cityService.save(expected); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void find() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.find(expected.getId())) + .thenReturn(Optional.of(expected)); + City actual = cityService.find(expected.getId()); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void delete() throws ElementNotFoundException { + City expected = createCity(); + cityService.delete(expected); + Mockito.verify(cityRepository).delete(expected); + } + + @Test + void findByName() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.findByName(expected.getName())) + .thenReturn(Optional.of(expected)); + City actual = cityService.findByName(expected.getName()); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void findAllByCanton() { + City city = createCity(); + Canton canton = city.getCanton(); + Mockito.when(cityRepository.findAllByCanton(canton)) + .thenReturn(Collections.singleton(city)); + Set expected = Set.of(city); + Set actual = cityService.findAllByCanton(canton); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void findAllByCountry() { + City city = createCity(); + Country country = city.getCanton().getCountry(); + Mockito.when(cityRepository.findAllByCountry(country)) + .thenReturn(Collections.singleton(city)); + Set expected = Set.of(city); + Set actual = cityService.findAllByCountry(country); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .setCanton(createCanton()) + .build(); + } + + private Canton createCanton() { + return Canton.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Canton" + System.currentTimeMillis()) + .setAbbreviation("SC-" + System.currentTimeMillis()) + .setCountry(createCountry()) + .build(); + } + + private Country createCountry() { + return Country.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Switzerland") + .build(); + } + +} \ No newline at end of file diff --git a/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoSpringStyle.java b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoSpringStyle.java new file mode 100644 index 0000000..2e88d73 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMockitoSpringStyle.java @@ -0,0 +1,126 @@ +package org.example.silenum.mockito.business.service; + +import java.time.ZonedDateTime; +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.unitils.reflectionassert.ReflectionAssert; + +@ExtendWith(SpringExtension.class) +class CityServiceImplTestMockitoSpringStyle { + + // System under Test (SuT) + private CityService cityService; + + // Mocks + @MockBean + private CityRepository cityRepository; + + @BeforeEach + void setUp() { + cityService = new CityServiceImpl(cityRepository); + } + + @Test + void save() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.save(expected)) + .thenReturn(Optional.of(expected)); + City actual = cityService.save(expected); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void find() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.find(expected.getId())) + .thenReturn(Optional.of(expected)); + City actual = cityService.find(expected.getId()); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void delete() throws ElementNotFoundException { + City expected = createCity(); + cityService.delete(expected); + Mockito.verify(cityRepository).delete(expected); + } + + @Test + void findByName() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.findByName(expected.getName())) + .thenReturn(Optional.of(expected)); + City actual = cityService.findByName(expected.getName()); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void findAllByCanton() { + City city = createCity(); + Canton canton = city.getCanton(); + Mockito.when(cityRepository.findAllByCanton(canton)) + .thenReturn(Collections.singleton(city)); + Set expected = Set.of(city); + Set actual = cityService.findAllByCanton(canton); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void findAllByCountry() { + City city = createCity(); + Country country = city.getCanton().getCountry(); + Mockito.when(cityRepository.findAllByCountry(country)) + .thenReturn(Collections.singleton(city)); + Set expected = Set.of(city); + Set actual = cityService.findAllByCountry(country); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .setCanton(createCanton()) + .build(); + } + + private Canton createCanton() { + return Canton.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Canton" + System.currentTimeMillis()) + .setAbbreviation("SC-" + System.currentTimeMillis()) + .setCountry(createCountry()) + .build(); + } + + private Country createCountry() { + return Country.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Switzerland") + .build(); + } + +} \ No newline at end of file diff --git a/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMultiWhenCalls.java b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMultiWhenCalls.java new file mode 100644 index 0000000..1b3c6d5 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestMultiWhenCalls.java @@ -0,0 +1,92 @@ +package org.example.silenum.mockito.business.service; + +import java.time.ZonedDateTime; +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.unitils.reflectionassert.ReflectionAssert; + +class CityServiceImplTestMultiWhenCalls { + + // System under Test (SuT) + private CityService cityService; + + // Mocks + private CityRepository cityRepository; + + @BeforeEach + void setUp() { + cityRepository = Mockito.mock(CityRepository.class); + cityService = new CityServiceImpl(cityRepository); + } + + @Test + void failingTestWhenRelyingOnOrder() throws ElementNotFoundException { + long id = 1; + City one = createCity(); + City two = createCity(); + City three = createCity(); + Mockito.when(cityRepository.find(id)).thenReturn(Optional.of(one)); + Mockito.when(cityRepository.find(id)).thenReturn(Optional.of(two)); + Mockito.when(cityRepository.find(id)).thenReturn(Optional.of(three)); + ReflectionAssert.assertReflectionEquals(one, cityService.find(id)); + ReflectionAssert.assertReflectionEquals(two, cityService.find(id)); + ReflectionAssert.assertReflectionEquals(three, cityService.find(id)); + } + + @Test + void successfulTestOnMultipleCalls() throws ElementNotFoundException { + long id = 1; + City one = createCity(); + City two = createCity(); + City three = createCity(); + Mockito.when(cityRepository.find(id)).thenReturn(Optional.of(one)); + Mockito.when(cityRepository.find(id)).thenReturn(Optional.of(two)); + Mockito.when(cityRepository.find(id)).thenReturn(Optional.of(three)); + ReflectionAssert.assertReflectionEquals(three, cityService.find(id)); + ReflectionAssert.assertReflectionEquals(three, cityService.find(id)); + ReflectionAssert.assertReflectionEquals(three, cityService.find(id)); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .setCanton(createCanton()) + .build(); + } + + private Canton createCanton() { + return Canton.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Canton" + System.currentTimeMillis()) + .setAbbreviation("SC-" + System.currentTimeMillis()) + .setCountry(createCountry()) + .build(); + } + + private Country createCountry() { + return Country.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Switzerland") + .build(); + } + +} \ No newline at end of file diff --git a/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestPlainMockito.java b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestPlainMockito.java new file mode 100644 index 0000000..40a1359 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestPlainMockito.java @@ -0,0 +1,15 @@ +package org.example.silenum.mockito.business.service; + +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.BeforeEach; +import org.mockito.Mockito; + +public class CityServiceImplTestPlainMockito { + + @BeforeEach + void setUp() { + CityRepository cityRepository = Mockito.mock(CityRepository.class); + CityService cityService = new CityServiceImpl(cityRepository); + } + +} diff --git a/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestVoidApproachAndThenThrow.java b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestVoidApproachAndThenThrow.java new file mode 100644 index 0000000..302579a --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/business/service/CityServiceImplTestVoidApproachAndThenThrow.java @@ -0,0 +1,83 @@ +package org.example.silenum.mockito.business.service; + +import java.time.ZonedDateTime; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class CityServiceImplTestVoidApproachAndThenThrow { + + // System under Test (SuT) + private CityService cityService; + + // Mocks + private CityRepository cityRepository; + + @BeforeEach + void setUp() { + cityRepository = Mockito.mock(CityRepository.class); + cityService = new CityServiceImpl(cityRepository); + } + + @Test + void find() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.find(expected.getId())) + .thenThrow(RuntimeException.class); + Assertions.assertThrows(RuntimeException.class, () -> cityRepository.find(expected.getId())); + } + + + @Test + void delete() throws ElementNotFoundException { + City expected = createCity(); + cityService.delete(expected); + // Causes a compiler error + // Mockito.when(cityRepository.delete()).thenThrow(RuntimeException.class); + Mockito.doThrow(RuntimeException.class).when(cityRepository).delete(expected); + Assertions.assertThrows(RuntimeException.class, () -> cityRepository.delete(expected)); + } + + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .setCanton(createCanton()) + .build(); + } + + private Canton createCanton() { + return Canton.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Canton" + System.currentTimeMillis()) + .setAbbreviation("SC-" + System.currentTimeMillis()) + .setCountry(createCountry()) + .build(); + } + + private Country createCountry() { + return Country.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Switzerland") + .build(); + } + +} \ No newline at end of file diff --git a/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontMockCollections.java b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontMockCollections.java new file mode 100644 index 0000000..2238f3c --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontMockCollections.java @@ -0,0 +1,38 @@ +package org.example.silenum.mockito.examples; + +import java.time.ZonedDateTime; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.domain.entity.City; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.unitils.reflectionassert.ReflectionAssert; + +public class ExampleDontMockCollections { + + @Test + void mockList() { + List cities = Mockito.mock(List.class); + + City city = createCity(); + City anotherCity = createCity(); + + Mockito.when(cities.get(0)).thenReturn(city); + Mockito.when(cities.get(1)).thenReturn(anotherCity); + + ReflectionAssert.assertReflectionEquals(city, cities.get(0)); + ReflectionAssert.assertReflectionEquals(anotherCity, cities.get(1)); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .build(); + } + +} diff --git a/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontMockCollectionsResolution.java b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontMockCollectionsResolution.java new file mode 100644 index 0000000..67b1bdd --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontMockCollectionsResolution.java @@ -0,0 +1,38 @@ +package org.example.silenum.mockito.examples; + +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.domain.entity.City; +import org.junit.jupiter.api.Test; +import org.unitils.reflectionassert.ReflectionAssert; + +public class ExampleDontMockCollectionsResolution { + + @Test + void mockListResolution() { + List cities = new ArrayList<>(); + + City city = createCity(); + City anotherCity = createCity(); + + cities.add(city); + cities.add(anotherCity); + + ReflectionAssert.assertReflectionEquals(city, cities.get(0)); + ReflectionAssert.assertReflectionEquals(anotherCity, cities.get(1)); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .build(); + } + +} diff --git a/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontMockValueTypes.java b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontMockValueTypes.java new file mode 100644 index 0000000..1742a22 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontMockValueTypes.java @@ -0,0 +1,18 @@ +package org.example.silenum.mockito.examples; + +import org.example.silenum.mockito.domain.entity.City; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +public class ExampleDontMockValueTypes { + + @Test + void mockCity() { + String cityName = "MockTown"; + City mockTown = Mockito.mock(City.class); + Mockito.when(mockTown.getName()).thenReturn(cityName); + Assertions.assertEquals(cityName, mockTown.getName()); + } + +} diff --git a/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontRecycleMocks.java b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontRecycleMocks.java new file mode 100644 index 0000000..3a58bf7 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontRecycleMocks.java @@ -0,0 +1,43 @@ +package org.example.silenum.mockito.examples; + +import org.example.silenum.mockito.business.service.CityService; +import org.example.silenum.mockito.business.service.CityServiceImpl; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class ExampleDontRecycleMocks { + + private CityService cityService; + + @Mock + private CityRepository cityRepository; + + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + cityService = new CityServiceImpl(cityRepository); + // Mockito declarations for testOne + // ... + // Mockito declarations for testTwo + // ... + } + + @Test + void testOne() { + // Test Case One + } + + @Test + void testTwo() { + // Test Case Two + } + + @Test + void test() { + // Another Test Case + } +} diff --git a/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontRecycleMocksResolution.java b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontRecycleMocksResolution.java new file mode 100644 index 0000000..c0685c7 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleDontRecycleMocksResolution.java @@ -0,0 +1,52 @@ +package org.example.silenum.mockito.examples; + +import org.example.silenum.mockito.business.service.CityService; +import org.example.silenum.mockito.business.service.CityServiceImpl; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class ExampleDontRecycleMocksResolution { + + private CityService cityService; + + @Mock + private CityRepository cityRepository; + + void initializeScenarioOne() { + // Mockito behaviour declarations + } + + void initializeScenarioTwo() { + // Mockito behaviour declarations + } + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + cityService = new CityServiceImpl(cityRepository); + } + + @Test + void testOne() { + initializeScenarioOne(); + // Test Case One + } + + @Test + void testTwo() { + initializeScenarioTwo(); + // Test Case Two + } + + @Test + void testThree() { + initializeScenarioOne(); + // ... + initializeScenarioTwo(); + // ... + // Another Test Case + } +} \ No newline at end of file diff --git a/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleMockitoReset.java b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleMockitoReset.java new file mode 100644 index 0000000..3c2635d --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleMockitoReset.java @@ -0,0 +1,80 @@ +package org.example.silenum.mockito.examples; + +import java.time.ZonedDateTime; +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.business.service.CityService; +import org.example.silenum.mockito.business.service.CityServiceImpl; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.unitils.reflectionassert.ReflectionAssert; + +public class ExampleMockitoReset { + + // System under Test (SuT) + private CityService cityService; + + // Mocks + private CityRepository cityRepository; + + @BeforeEach + void setUp() { + cityRepository = Mockito.mock(CityRepository.class); + cityService = new CityServiceImpl(cityRepository); + } + + @Test + void findAndDelete() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.find(expected.getId())).thenReturn(Optional.of(expected)); + City actual = cityService.find(expected.getId()); + ReflectionAssert.assertReflectionEquals(expected, actual); + cityService.delete(expected); + Mockito.verify(cityRepository).delete(expected); + Mockito.reset(cityRepository); + Mockito.when(cityRepository.find(expected.getId())).thenReturn(Optional.empty()); + Assertions.assertThrows(ElementNotFoundException.class, () -> cityService.find(expected.getId())); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .setCanton(createCanton()) + .build(); + } + + private Canton createCanton() { + return Canton.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Canton" + System.currentTimeMillis()) + .setAbbreviation("SC-" + System.currentTimeMillis()) + .setCountry(createCountry()) + .build(); + } + + private Country createCountry() { + return Country.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Switzerland") + .build(); + } + +} diff --git a/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleMockitoResetResolution.java b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleMockitoResetResolution.java new file mode 100644 index 0000000..b32cb31 --- /dev/null +++ b/mockito/src/test/java/org/example/silenum/mockito/examples/ExampleMockitoResetResolution.java @@ -0,0 +1,89 @@ +package org.example.silenum.mockito.examples; + +import java.time.ZonedDateTime; +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; + +import org.example.silenum.mockito.business.exception.ElementNotFoundException; +import org.example.silenum.mockito.business.service.CityService; +import org.example.silenum.mockito.business.service.CityServiceImpl; +import org.example.silenum.mockito.domain.entity.Canton; +import org.example.silenum.mockito.domain.entity.City; +import org.example.silenum.mockito.domain.entity.Country; +import org.example.silenum.mockito.domain.repository.CityRepository; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.unitils.reflectionassert.ReflectionAssert; + +public class ExampleMockitoResetResolution { + + // System under Test (SuT) + private CityService cityService; + + // Mocks + private CityRepository cityRepository; + + @BeforeEach + void setUp() { + cityRepository = Mockito.mock(CityRepository.class); + cityService = new CityServiceImpl(cityRepository); + } + + @Test + void find() throws ElementNotFoundException { + City expected = createCity(); + Mockito.when(cityRepository.find(expected.getId())).thenReturn(Optional.of(expected)); + City actual = cityService.find(expected.getId()); + ReflectionAssert.assertReflectionEquals(expected, actual); + } + + @Test + void delete() throws ElementNotFoundException { + City expected = createCity(); + cityService.delete(expected); + Mockito.verify(cityRepository).delete(expected); + } + + @Test + void findThrows() { + City expected = createCity(); + Mockito.when(cityRepository.find(expected.getId())).thenReturn(Optional.empty()); + Assertions.assertThrows(ElementNotFoundException.class, () -> cityService.find(expected.getId())); + } + + private City createCity() { + return City.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Test City " + System.currentTimeMillis()) + .setCanton(createCanton()) + .build(); + } + + private Canton createCanton() { + return Canton.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Swiss Canton" + System.currentTimeMillis()) + .setAbbreviation("SC-" + System.currentTimeMillis()) + .setCountry(createCountry()) + .build(); + } + + private Country createCountry() { + return Country.builder() + .id(System.currentTimeMillis()) + .version(ThreadLocalRandom.current().nextInt()) + .created(ZonedDateTime.now().minusDays(1L)) + .updated(ZonedDateTime.now()) + .setName("Switzerland") + .build(); + } + +}