Merge remote-tracking branch 'origin/main' into persistence-modules
This commit is contained in:
commit
05d80c840d
5
spring-boot-modules/spring-boot-testing/.gitignore
vendored
Normal file
5
spring-boot-modules/spring-boot-testing/.gitignore
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
/target/
|
||||||
|
.settings/
|
||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
|
1
spring-boot-modules/spring-boot-testing/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
1
spring-boot-modules/spring-boot-testing/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
|
18
spring-boot-modules/spring-boot-testing/README.md
Normal file
18
spring-boot-modules/spring-boot-testing/README.md
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
## Spring Boot Testing
|
||||||
|
|
||||||
|
This module contains articles about Spring Boot testing
|
||||||
|
|
||||||
|
### The Course
|
||||||
|
|
||||||
|
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing)
|
||||||
|
- [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test)
|
||||||
|
- [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis)
|
||||||
|
- [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties)
|
||||||
|
- [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution)
|
||||||
|
- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing)
|
||||||
|
- [Fixing the NoSuchMethodError JUnit Error](https://www.baeldung.com/junit-nosuchmethoderror)
|
||||||
|
- More articles: [[more -->]](../spring-boot-testing-2)
|
227
spring-boot-modules/spring-boot-testing/mvnw
vendored
Normal file
227
spring-boot-modules/spring-boot-testing/mvnw
vendored
Normal file
@ -0,0 +1,227 @@
|
|||||||
|
#!/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
|
||||||
|
#
|
||||||
|
# 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.
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
# Maven2 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)`"
|
||||||
|
# TODO classpath?
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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 "$@"
|
145
spring-boot-modules/spring-boot-testing/mvnw.cmd
vendored
Normal file
145
spring-boot-modules/spring-boot-testing/mvnw.cmd
vendored
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
@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 Maven2 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 key stroke 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 my 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
|
||||||
|
|
||||||
|
%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%
|
149
spring-boot-modules/spring-boot-testing/pom.xml
Normal file
149
spring-boot-modules/spring-boot-testing/pom.xml
Normal file
@ -0,0 +1,149 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>spring-boot-testing</artifactId>
|
||||||
|
<name>spring-boot-testing</name>
|
||||||
|
<packaging>war</packaging>
|
||||||
|
<description>This is simple boot application for demonstrating testing features.</description>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.spring-boot-modules</groupId>
|
||||||
|
<artifactId>spring-boot-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-bom</artifactId>
|
||||||
|
<version>${log4j2.version}</version>
|
||||||
|
<scope>import</scope>
|
||||||
|
<type>pom</type>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<!-- Embedded Redis Server -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>it.ozimov</groupId>
|
||||||
|
<artifactId>embedded-redis</artifactId>
|
||||||
|
<version>${redis.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<!-- Spock & Spring -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.spockframework</groupId>
|
||||||
|
<artifactId>spock-core</artifactId>
|
||||||
|
<version>${spock.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.spockframework</groupId>
|
||||||
|
<artifactId>spock-spring</artifactId>
|
||||||
|
<version>${spock.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>spring-boot-testing</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>pl.project13.maven</groupId>
|
||||||
|
<artifactId>git-commit-id-plugin</artifactId>
|
||||||
|
<version>${git-commit-id-plugin.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>get-the-git-infos</id>
|
||||||
|
<goals>
|
||||||
|
<goal>revision</goal>
|
||||||
|
</goals>
|
||||||
|
<phase>initialize</phase>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>validate-the-git-infos</id>
|
||||||
|
<goals>
|
||||||
|
<goal>validateRevision</goal>
|
||||||
|
</goals>
|
||||||
|
<phase>package</phase>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<generateGitPropertiesFile>true</generateGitPropertiesFile>
|
||||||
|
<generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.gmavenplus</groupId>
|
||||||
|
<artifactId>gmavenplus-plugin</artifactId>
|
||||||
|
<version>${gmavenplus-plugin.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>compileTests</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- The main class to start by executing java -jar -->
|
||||||
|
<start-class>com.baeldung.boot.Application</start-class>
|
||||||
|
<git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version>
|
||||||
|
<spock.version>1.2-groovy-2.4</spock.version>
|
||||||
|
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||||
|
<redis.version>0.7.2</redis.version>
|
||||||
|
<spring-boot.version>2.5.0</spring-boot.version>
|
||||||
|
<log4j2.version>2.17.1</log4j2.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.boot;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class Application {
|
||||||
|
private static ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
applicationContext = SpringApplication.run(Application.class, args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
public class Credentials {
|
||||||
|
|
||||||
|
private String username;
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
public Credentials(String username, String password) {
|
||||||
|
this.username = username;
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username) {
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
|
||||||
|
import org.springframework.core.convert.converter.Converter;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@ConfigurationPropertiesBinding
|
||||||
|
public class CustomCredentialsConverter implements Converter<String, Credentials> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Credentials convert(String source) {
|
||||||
|
String[] data = source.split(",");
|
||||||
|
return new Credentials(data[0], data[1]);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,59 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import javax.validation.Valid;
|
||||||
|
import javax.validation.constraints.Email;
|
||||||
|
import javax.validation.constraints.NotBlank;
|
||||||
|
import javax.validation.constraints.NotEmpty;
|
||||||
|
import javax.validation.constraints.NotNull;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.PropertySource;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "validate")
|
||||||
|
@PropertySource("classpath:property-validation.properties")
|
||||||
|
@Validated
|
||||||
|
public class MailServer {
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@NotEmpty
|
||||||
|
private Map<String, @NotBlank String> propertiesMap;
|
||||||
|
|
||||||
|
@Valid
|
||||||
|
private MailConfig mailConfig = new MailConfig();
|
||||||
|
|
||||||
|
public static class MailConfig {
|
||||||
|
|
||||||
|
@NotBlank
|
||||||
|
@Email
|
||||||
|
private String address;
|
||||||
|
|
||||||
|
public String getAddress() {
|
||||||
|
return address;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAddress(String address) {
|
||||||
|
this.address = address;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> getPropertiesMap() {
|
||||||
|
return propertiesMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPropertiesMap(Map<String, String> propertiesMap) {
|
||||||
|
this.propertiesMap = propertiesMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MailConfig getMailConfig() {
|
||||||
|
return mailConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMailConfig(MailConfig mailConfig) {
|
||||||
|
this.mailConfig = mailConfig;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,67 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.boot.convert.DataSizeUnit;
|
||||||
|
import org.springframework.boot.convert.DurationUnit;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.util.unit.DataSize;
|
||||||
|
import org.springframework.util.unit.DataUnit;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "server")
|
||||||
|
public class PropertyConversion {
|
||||||
|
|
||||||
|
private DataSize uploadSpeed;
|
||||||
|
|
||||||
|
@DataSizeUnit(DataUnit.GIGABYTES)
|
||||||
|
private DataSize downloadSpeed;
|
||||||
|
|
||||||
|
private Duration backupDay;
|
||||||
|
|
||||||
|
@DurationUnit(ChronoUnit.HOURS)
|
||||||
|
private Duration backupHour;
|
||||||
|
|
||||||
|
private Credentials credentials;
|
||||||
|
|
||||||
|
public Duration getBackupDay() {
|
||||||
|
return backupDay;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBackupDay(Duration backupDay) {
|
||||||
|
this.backupDay = backupDay;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Duration getBackupHour() {
|
||||||
|
return backupHour;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBackupHour(Duration backupHour) {
|
||||||
|
this.backupHour = backupHour;
|
||||||
|
}
|
||||||
|
|
||||||
|
public DataSize getUploadSpeed() {
|
||||||
|
return uploadSpeed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUploadSpeed(DataSize uploadSpeed) {
|
||||||
|
this.uploadSpeed = uploadSpeed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public DataSize getDownloadSpeed() {
|
||||||
|
return downloadSpeed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDownloadSpeed(DataSize downloadSpeed) {
|
||||||
|
this.downloadSpeed = downloadSpeed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Credentials getCredentials() {
|
||||||
|
return credentials;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCredentials(Credentials credentials) {
|
||||||
|
this.credentials = credentials;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "server")
|
||||||
|
public class ServerConfig {
|
||||||
|
|
||||||
|
private Address address;
|
||||||
|
private Map<String, String> resourcesPath;
|
||||||
|
|
||||||
|
public static class Address {
|
||||||
|
|
||||||
|
private String ip;
|
||||||
|
|
||||||
|
public String getIp() {
|
||||||
|
return ip;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIp(String ip) {
|
||||||
|
this.ip = ip;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Address getAddress() {
|
||||||
|
return address;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAddress(Address address) {
|
||||||
|
this.address = address;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> getResourcesPath() {
|
||||||
|
return resourcesPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setResourcesPath(Map<String, String> resourcesPath) {
|
||||||
|
this.resourcesPath = resourcesPath;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class ServerConfigFactory {
|
||||||
|
|
||||||
|
@Bean(name = "default_bean")
|
||||||
|
@ConfigurationProperties(prefix = "server.default")
|
||||||
|
public ServerConfig getDefaultConfigs() {
|
||||||
|
return new ServerConfig();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.boot.controller.rest;
|
||||||
|
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
public class HomeController {
|
||||||
|
|
||||||
|
@GetMapping("/")
|
||||||
|
public String salutation() {
|
||||||
|
return "Welcome !";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.boot.controller.rest;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/hello")
|
||||||
|
public class WebController {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public String salutation() {
|
||||||
|
return "Hello " + Optional.ofNullable(name).orElse("world") + '!';
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping
|
||||||
|
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||||
|
public void setName(@RequestBody final String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping
|
||||||
|
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||||
|
public void resetToDefault() {
|
||||||
|
this.name = null;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.boot.embeddedRedis.configuration;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||||
|
import org.springframework.data.redis.core.RedisTemplate;
|
||||||
|
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableRedisRepositories
|
||||||
|
public class RedisConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public LettuceConnectionFactory redisConnectionFactory(final RedisProperties redisProperties) {
|
||||||
|
return new LettuceConnectionFactory(redisProperties.getRedisHost(), redisProperties.getRedisPort());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public RedisTemplate<?, ?> redisTemplate(final LettuceConnectionFactory connectionFactory) {
|
||||||
|
RedisTemplate<byte[], byte[]> template = new RedisTemplate<>();
|
||||||
|
template.setConnectionFactory(connectionFactory);
|
||||||
|
return template;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.boot.embeddedRedis.configuration;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class RedisProperties {
|
||||||
|
private final int redisPort;
|
||||||
|
private final String redisHost;
|
||||||
|
|
||||||
|
public RedisProperties(@Value("${spring.redis.port}") final int redisPort, @Value("${spring.redis.host}") final String redisHost) {
|
||||||
|
this.redisPort = redisPort;
|
||||||
|
this.redisHost = redisHost;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getRedisPort() {
|
||||||
|
return redisPort;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRedisHost() {
|
||||||
|
return redisHost;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.boot.embeddedRedis.domain;
|
||||||
|
|
||||||
|
import org.springframework.data.annotation.Id;
|
||||||
|
import org.springframework.data.redis.core.RedisHash;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RedisHash("user")
|
||||||
|
public class User {
|
||||||
|
@Id private UUID id;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public User(UUID id, String name) {
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UUID getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.boot.embeddedRedis.domain.repository;
|
||||||
|
|
||||||
|
import com.baeldung.boot.embeddedRedis.domain.User;
|
||||||
|
import org.springframework.data.repository.CrudRepository;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface UserRepository extends CrudRepository<User, UUID> {
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import javax.persistence.Entity;
|
||||||
|
import javax.persistence.GeneratedValue;
|
||||||
|
import javax.persistence.GenerationType;
|
||||||
|
import javax.persistence.Id;
|
||||||
|
import javax.persistence.Table;
|
||||||
|
import javax.validation.constraints.Size;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "person")
|
||||||
|
public class Employee {
|
||||||
|
|
||||||
|
public Employee() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Employee(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Size(min = 3, max = 20)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
private Date birthday;
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
@Transactional
|
||||||
|
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
|
||||||
|
|
||||||
|
public Employee findByName(String name);
|
||||||
|
|
||||||
|
public List<Employee> findAll();
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api")
|
||||||
|
public class EmployeeRestController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeService employeeService;
|
||||||
|
|
||||||
|
@PostMapping("/employees")
|
||||||
|
public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
|
||||||
|
HttpStatus status = HttpStatus.CREATED;
|
||||||
|
Employee saved = employeeService.save(employee);
|
||||||
|
return new ResponseEntity<>(saved, status);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/employees")
|
||||||
|
public List<Employee> getAllEmployees() {
|
||||||
|
return employeeService.getAllEmployees();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface EmployeeService {
|
||||||
|
|
||||||
|
public Employee getEmployeeById(Long id);
|
||||||
|
|
||||||
|
public Employee getEmployeeByName(String name);
|
||||||
|
|
||||||
|
public List<Employee> getAllEmployees();
|
||||||
|
|
||||||
|
public boolean exists(String email);
|
||||||
|
|
||||||
|
public Employee save(Employee employee);
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Transactional
|
||||||
|
public class EmployeeServiceImpl implements EmployeeService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeRepository employeeRepository;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Employee getEmployeeById(Long id) {
|
||||||
|
return employeeRepository.findById(id).orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Employee getEmployeeByName(String name) {
|
||||||
|
return employeeRepository.findByName(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean exists(String name) {
|
||||||
|
if (employeeRepository.findByName(name) != null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Employee save(Employee employee) {
|
||||||
|
return employeeRepository.save(employee);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Employee> getAllEmployees() {
|
||||||
|
return employeeRepository.findAll();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.prevent.commandline.application.runner.execution;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class ApplicationCommandLineRunnerApp {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(ApplicationCommandLineRunnerApp.class, args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.prevent.commandline.application.runner.execution;
|
||||||
|
|
||||||
|
import org.springframework.boot.ApplicationArguments;
|
||||||
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Profile("!test")
|
||||||
|
@ConditionalOnProperty(
|
||||||
|
prefix = "application.runner",
|
||||||
|
value = "enabled",
|
||||||
|
havingValue = "true",
|
||||||
|
matchIfMissing = true)
|
||||||
|
@Component
|
||||||
|
public class ApplicationRunnerTaskExecutor implements ApplicationRunner {
|
||||||
|
private TaskService taskService;
|
||||||
|
|
||||||
|
public ApplicationRunnerTaskExecutor(TaskService taskService) {
|
||||||
|
this.taskService = taskService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(ApplicationArguments args) throws Exception {
|
||||||
|
taskService.execute("application runner task");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.prevent.commandline.application.runner.execution;
|
||||||
|
|
||||||
|
import org.springframework.boot.CommandLineRunner;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Profile("!test")
|
||||||
|
@ConditionalOnProperty(
|
||||||
|
prefix = "command.line.runner",
|
||||||
|
value = "enabled",
|
||||||
|
havingValue = "true",
|
||||||
|
matchIfMissing = true)
|
||||||
|
@Component
|
||||||
|
public class CommandLineTaskExecutor implements CommandLineRunner {
|
||||||
|
private TaskService taskService;
|
||||||
|
|
||||||
|
public CommandLineTaskExecutor(TaskService taskService) {
|
||||||
|
this.taskService = taskService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(String... args) throws Exception {
|
||||||
|
taskService.execute("command line runner task");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.prevent.commandline.application.runner.execution;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class TaskService {
|
||||||
|
private static Logger logger = LoggerFactory.getLogger(TaskService.class);
|
||||||
|
|
||||||
|
public void execute(String task) {
|
||||||
|
logger.info("do " + task);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
|
||||||
|
# test properties
|
||||||
|
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
|
@ -0,0 +1,8 @@
|
|||||||
|
# embedded redis
|
||||||
|
spring.redis.host= localhost
|
||||||
|
spring.redis.port= 6379
|
||||||
|
|
||||||
|
# security
|
||||||
|
spring.security.user.name=john
|
||||||
|
spring.security.user.password=123
|
||||||
|
|
@ -0,0 +1,8 @@
|
|||||||
|
jdbc.driverClassName=org.h2.Driver
|
||||||
|
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
||||||
|
jdbc.user=sa
|
||||||
|
jdbc.pass=sa
|
||||||
|
|
||||||
|
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||||
|
hibernate.show_sql=true
|
||||||
|
hibernate.hbm2ddl.auto=create-drop
|
@ -0,0 +1,4 @@
|
|||||||
|
validate.propertiesMap.first=prop1
|
||||||
|
validate.propertiesMap.second=prop2
|
||||||
|
|
||||||
|
validate.mail_config.address=user1@test
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.boot
|
||||||
|
|
||||||
|
import com.baeldung.boot.controller.rest.WebController
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest
|
||||||
|
import spock.lang.Narrative
|
||||||
|
import spock.lang.Specification
|
||||||
|
import spock.lang.Title
|
||||||
|
|
||||||
|
@Title("Application Specification")
|
||||||
|
@Narrative("Specification which beans are expected")
|
||||||
|
@SpringBootTest
|
||||||
|
class LoadContextTest extends Specification {
|
||||||
|
|
||||||
|
@Autowired(required = false)
|
||||||
|
private WebController webController
|
||||||
|
|
||||||
|
|
||||||
|
def "when context is loaded then all expected beans are created"() {
|
||||||
|
expect: "the WebController is created"
|
||||||
|
webController
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.boot
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired
|
||||||
|
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
|
||||||
|
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest
|
||||||
|
import org.springframework.test.web.servlet.MockMvc
|
||||||
|
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
|
||||||
|
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
|
||||||
|
import spock.lang.Narrative
|
||||||
|
import spock.lang.Specification
|
||||||
|
import spock.lang.Title
|
||||||
|
|
||||||
|
@Title("WebController Specification")
|
||||||
|
@Narrative("The Specification of the behaviour of the WebController. It can greet a person, change the name and reset it to 'world'")
|
||||||
|
@SpringBootTest
|
||||||
|
@AutoConfigureMockMvc
|
||||||
|
@EnableAutoConfiguration(exclude= SecurityAutoConfiguration.class)
|
||||||
|
class WebControllerTest extends Specification {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MockMvc mvc
|
||||||
|
|
||||||
|
def "when get is performed then the response has status 200 and content is 'Hello world!'"() {
|
||||||
|
expect: "Status is 200 and the response is 'Hello world!'"
|
||||||
|
mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello world!"
|
||||||
|
}
|
||||||
|
|
||||||
|
def "when set and delete are performed then the response has status 204 and content changes as expected"() {
|
||||||
|
given: "a new name"
|
||||||
|
def NAME = "Emmy"
|
||||||
|
|
||||||
|
when: "the name is set"
|
||||||
|
mvc.perform(MockMvcRequestBuilders.put("/hello").content(NAME)).andExpect(MockMvcResultMatchers.status().isNoContent())
|
||||||
|
|
||||||
|
then: "the salutation uses the new name"
|
||||||
|
mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello $NAME!"
|
||||||
|
|
||||||
|
when: "the name is deleted"
|
||||||
|
mvc.perform(MockMvcRequestBuilders.delete("/hello")).andExpect(MockMvcResultMatchers.status().isNoContent())
|
||||||
|
|
||||||
|
then: "the salutation uses the default name"
|
||||||
|
mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello world!"
|
||||||
|
}
|
||||||
|
}
|
Binary file not shown.
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.autoconfig.exclude;
|
||||||
|
|
||||||
|
import com.baeldung.boot.Application;
|
||||||
|
import io.restassured.RestAssured;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||||
|
import org.springframework.boot.web.server.LocalServerPort;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||||
|
@TestPropertySource(properties = "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration")
|
||||||
|
public class ExcludeAutoConfig1IntegrationTest {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates the random port the test server is listening on.
|
||||||
|
*/
|
||||||
|
@LocalServerPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() {
|
||||||
|
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
|
||||||
|
assertEquals(HttpStatus.OK.value(), statusCode);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.autoconfig.exclude;
|
||||||
|
|
||||||
|
import com.baeldung.boot.Application;
|
||||||
|
import io.restassured.RestAssured;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||||
|
import org.springframework.boot.web.server.LocalServerPort;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
public class ExcludeAutoConfig2IntegrationTest {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates the random port the test server is listening on.
|
||||||
|
*/
|
||||||
|
@LocalServerPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() {
|
||||||
|
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
|
||||||
|
assertEquals(HttpStatus.OK.value(), statusCode);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.autoconfig.exclude;
|
||||||
|
|
||||||
|
import com.baeldung.boot.Application;
|
||||||
|
import io.restassured.RestAssured;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||||
|
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||||
|
import org.springframework.boot.web.server.LocalServerPort;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||||
|
@EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class)
|
||||||
|
public class ExcludeAutoConfig3IntegrationTest {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates the random port the test server is listening on.
|
||||||
|
*/
|
||||||
|
@LocalServerPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() {
|
||||||
|
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
|
||||||
|
assertEquals(HttpStatus.OK.value(), statusCode);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.autoconfig.exclude;
|
||||||
|
|
||||||
|
import io.restassured.RestAssured;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||||
|
import org.springframework.boot.web.server.LocalServerPort;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||||
|
public class ExcludeAutoConfig4IntegrationTest {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates the random port the test server is listening on.
|
||||||
|
*/
|
||||||
|
@LocalServerPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() {
|
||||||
|
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
|
||||||
|
assertEquals(HttpStatus.OK.value(), statusCode);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.autoconfig.exclude;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||||
|
|
||||||
|
@SpringBootApplication(scanBasePackages="com.baeldung.boot", exclude=SecurityAutoConfiguration.class)
|
||||||
|
public class TestApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(TestApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.boot;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = Application.class)
|
||||||
|
public class SpringContextTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.boot.autoconfig;
|
||||||
|
|
||||||
|
import com.baeldung.boot.Application;
|
||||||
|
import io.restassured.RestAssured;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||||
|
import org.springframework.boot.web.server.LocalServerPort;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||||
|
public class AutoConfigIntegrationTest {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates the random port the test server is listening on.
|
||||||
|
*/
|
||||||
|
@LocalServerPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNoAuthentication_whenAccessHome_thenUnauthorized() {
|
||||||
|
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
|
||||||
|
assertEquals(HttpStatus.UNAUTHORIZED.value(), statusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAuthentication_whenAccessHome_thenOK() {
|
||||||
|
int statusCode = RestAssured.given().auth().basic("john", "123").get("http://localhost:" + port).statusCode();
|
||||||
|
assertEquals(HttpStatus.OK.value(), statusCode);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@EnableConfigurationProperties(value = ServerConfig.class)
|
||||||
|
@ContextConfiguration(classes = ServerConfigFactory.class)
|
||||||
|
@TestPropertySource("classpath:server-config-test.properties")
|
||||||
|
public class BindingPropertiesToBeanMethodsUnitTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("default_bean")
|
||||||
|
private ServerConfig serverConfig;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenBeanAnnotatedMethod_whenBindingProperties_thenAllFieldsAreSet() {
|
||||||
|
assertEquals("192.168.0.2", serverConfig.getAddress()
|
||||||
|
.getIp());
|
||||||
|
|
||||||
|
Map<String, String> expectedResourcesPath = new HashMap<>();
|
||||||
|
expectedResourcesPath.put("imgs", "/root/def/imgs");
|
||||||
|
assertEquals(expectedResourcesPath, serverConfig.getResourcesPath());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@EnableConfigurationProperties(value = ServerConfig.class)
|
||||||
|
@TestPropertySource("classpath:server-config-test.properties")
|
||||||
|
public class BindingPropertiesToUserDefinedPOJOUnitTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ServerConfig serverConfig;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenUserDefinedPOJO_whenBindingPropertiesFile_thenAllFieldsAreSet() {
|
||||||
|
assertEquals("192.168.0.1", serverConfig.getAddress()
|
||||||
|
.getIp());
|
||||||
|
|
||||||
|
Map<String, String> expectedResourcesPath = new HashMap<>();
|
||||||
|
expectedResourcesPath.put("imgs", "/root/imgs");
|
||||||
|
assertEquals(expectedResourcesPath, serverConfig.getResourcesPath());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@ContextConfiguration(initializers = ConfigDataApplicationContextInitializer.class)
|
||||||
|
@EnableConfigurationProperties(value = ServerConfig.class)
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
public class BindingYMLPropertiesUnitTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ServerConfig serverConfig;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenBindingYMLConfigFile_thenAllFieldsAreSet() {
|
||||||
|
assertEquals("192.168.0.4", serverConfig.getAddress()
|
||||||
|
.getIp());
|
||||||
|
|
||||||
|
Map<String, String> expectedResourcesPath = new HashMap<>();
|
||||||
|
expectedResourcesPath.put("imgs", "/etc/test/imgs");
|
||||||
|
assertEquals(expectedResourcesPath, serverConfig.getResourcesPath());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@EnableConfigurationProperties(value = MailServer.class)
|
||||||
|
@TestPropertySource(properties = { "validate.mail_config.address=new_user@test" })
|
||||||
|
public class OverridingConfigurationPropertiesUnitTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MailServer mailServer;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenUsingPropertiesAttribute_whenAssiginingNewValueToProprty_thenSpringUsesNewValue() {
|
||||||
|
assertEquals("new_user@test", mailServer.getMailConfig()
|
||||||
|
.getAddress());
|
||||||
|
|
||||||
|
Map<String, String> expectedMap = new HashMap<>();
|
||||||
|
expectedMap.put("first", "prop1");
|
||||||
|
expectedMap.put("second", "prop2");
|
||||||
|
assertEquals(expectedMap, mailServer.getPropertiesMap());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,39 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import javax.validation.Validation;
|
||||||
|
import javax.validation.Validator;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@EnableConfigurationProperties(value = MailServer.class)
|
||||||
|
@TestPropertySource("classpath:property-validation-test.properties")
|
||||||
|
public class PropertyValidationUnitTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MailServer mailServer;
|
||||||
|
|
||||||
|
private static Validator propertyValidator;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
public static void setup() {
|
||||||
|
propertyValidator = Validation.buildDefaultValidatorFactory()
|
||||||
|
.getValidator();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenBindingPropertiesToValidatedBeans_thenConstrainsAreChecked() {
|
||||||
|
assertEquals(0, propertyValidator.validate(mailServer.getPropertiesMap())
|
||||||
|
.size());
|
||||||
|
assertEquals(0, propertyValidator.validate(mailServer.getMailConfig())
|
||||||
|
.size());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.boot.configurationproperties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
import org.springframework.util.unit.DataSize;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@EnableConfigurationProperties(value = PropertyConversion.class)
|
||||||
|
@ContextConfiguration(classes = CustomCredentialsConverter.class)
|
||||||
|
@TestPropertySource("classpath:spring-conversion-test.properties")
|
||||||
|
public class SpringPropertiesConversionUnitTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private PropertyConversion propertyConversion;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingSpringDefaultSizeConversion_thenDataSizeObjectIsSet() {
|
||||||
|
assertEquals(DataSize.ofMegabytes(500), propertyConversion.getUploadSpeed());
|
||||||
|
assertEquals(DataSize.ofGigabytes(10), propertyConversion.getDownloadSpeed());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingSpringDefaultDurationConversion_thenDurationObjectIsSet() {
|
||||||
|
assertEquals(Duration.ofDays(1), propertyConversion.getBackupDay());
|
||||||
|
assertEquals(Duration.ofHours(8), propertyConversion.getBackupHour());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRegisteringCustomCredentialsConverter_thenCredentialsAreParsed() {
|
||||||
|
assertEquals("user", propertyConversion.getCredentials()
|
||||||
|
.getUsername());
|
||||||
|
assertEquals("123", propertyConversion.getCredentials()
|
||||||
|
.getPassword());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.boot.embeddedRedis;
|
||||||
|
|
||||||
|
import com.baeldung.boot.embeddedRedis.configuration.RedisProperties;
|
||||||
|
import org.springframework.boot.test.context.TestConfiguration;
|
||||||
|
import redis.embedded.RedisServer;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
import javax.annotation.PreDestroy;
|
||||||
|
|
||||||
|
@TestConfiguration
|
||||||
|
public class TestRedisConfiguration {
|
||||||
|
|
||||||
|
private final RedisServer redisServer;
|
||||||
|
|
||||||
|
public TestRedisConfiguration(final RedisProperties redisProperties) {
|
||||||
|
this.redisServer = new RedisServer(redisProperties.getRedisPort());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void postConstruct() {
|
||||||
|
redisServer.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void preDestroy() {
|
||||||
|
redisServer.stop();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.boot.embeddedRedis.domain.repository;
|
||||||
|
|
||||||
|
import com.baeldung.boot.embeddedRedis.TestRedisConfiguration;
|
||||||
|
import com.baeldung.boot.embeddedRedis.domain.User;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = TestRedisConfiguration.class)
|
||||||
|
public class UserRepositoryIntegrationTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserRepository userRepository;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldSaveUser_toRedis() {
|
||||||
|
final UUID id = UUID.randomUUID();
|
||||||
|
final User user = new User(id, "name");
|
||||||
|
|
||||||
|
final User saved = userRepository.save(user);
|
||||||
|
|
||||||
|
assertNotNull(saved);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,73 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.Matchers.hasSize;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
|
import static org.mockito.Mockito.reset;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
import org.mockito.internal.verification.VerificationModeFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||||
|
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
|
||||||
|
import com.baeldung.boot.testing.Employee;
|
||||||
|
import com.baeldung.boot.testing.EmployeeRestController;
|
||||||
|
import com.baeldung.boot.testing.EmployeeService;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@WebMvcTest(value = EmployeeRestController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class)
|
||||||
|
public class EmployeeControllerIntegrationTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MockMvc mvc;
|
||||||
|
|
||||||
|
@MockBean
|
||||||
|
private EmployeeService service;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPostEmployee_thenCreateEmployee() throws Exception {
|
||||||
|
Employee alex = new Employee("alex");
|
||||||
|
given(service.save(Mockito.any())).willReturn(alex);
|
||||||
|
|
||||||
|
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(alex))).andExpect(status().isCreated()).andExpect(jsonPath("$.name", is("alex")));
|
||||||
|
verify(service, VerificationModeFactory.times(1)).save(Mockito.any());
|
||||||
|
reset(service);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmployees_whenGetEmployees_thenReturnJsonArray() throws Exception {
|
||||||
|
Employee alex = new Employee("alex");
|
||||||
|
Employee john = new Employee("john");
|
||||||
|
Employee bob = new Employee("bob");
|
||||||
|
|
||||||
|
List<Employee> allEmployees = Arrays.asList(alex, john, bob);
|
||||||
|
|
||||||
|
given(service.getAllEmployees()).willReturn(allEmployees);
|
||||||
|
|
||||||
|
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(3))).andExpect(jsonPath("$[0].name", is(alex.getName()))).andExpect(jsonPath("$[1].name", is(john.getName())))
|
||||||
|
.andExpect(jsonPath("$[2].name", is(bob.getName())));
|
||||||
|
verify(service, VerificationModeFactory.times(1)).getAllEmployees();
|
||||||
|
reset(service);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,72 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||||
|
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import com.baeldung.boot.testing.Employee;
|
||||||
|
import com.baeldung.boot.testing.EmployeeRepository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@DataJpaTest
|
||||||
|
public class EmployeeRepositoryIntegrationTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private TestEntityManager entityManager;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeRepository employeeRepository;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindByName_thenReturnEmployee() {
|
||||||
|
Employee alex = new Employee("alex");
|
||||||
|
entityManager.persistAndFlush(alex);
|
||||||
|
|
||||||
|
Employee found = employeeRepository.findByName(alex.getName());
|
||||||
|
assertThat(found.getName()).isEqualTo(alex.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInvalidName_thenReturnNull() {
|
||||||
|
Employee fromDb = employeeRepository.findByName("doesNotExist");
|
||||||
|
assertThat(fromDb).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindById_thenReturnEmployee() {
|
||||||
|
Employee emp = new Employee("test");
|
||||||
|
entityManager.persistAndFlush(emp);
|
||||||
|
|
||||||
|
Employee fromDb = employeeRepository.findById(emp.getId()).orElse(null);
|
||||||
|
assertThat(fromDb.getName()).isEqualTo(emp.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInvalidId_thenReturnNull() {
|
||||||
|
Employee fromDb = employeeRepository.findById(-11l).orElse(null);
|
||||||
|
assertThat(fromDb).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSetOfEmployees_whenFindAll_thenReturnAllEmployees() {
|
||||||
|
Employee alex = new Employee("alex");
|
||||||
|
Employee ron = new Employee("ron");
|
||||||
|
Employee bob = new Employee("bob");
|
||||||
|
|
||||||
|
entityManager.persist(alex);
|
||||||
|
entityManager.persist(bob);
|
||||||
|
entityManager.persist(ron);
|
||||||
|
entityManager.flush();
|
||||||
|
|
||||||
|
List<Employee> allEmployees = employeeRepository.findAll();
|
||||||
|
|
||||||
|
assertThat(allEmployees).hasSize(3).extracting(Employee::getName).containsOnly(alex.getName(), ron.getName(), bob.getName());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,86 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
|
||||||
|
import static org.hamcrest.Matchers.hasSize;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||||
|
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||||
|
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
|
||||||
|
import com.baeldung.boot.Application;
|
||||||
|
import com.baeldung.boot.testing.Employee;
|
||||||
|
import com.baeldung.boot.testing.EmployeeRepository;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = Application.class)
|
||||||
|
@AutoConfigureMockMvc
|
||||||
|
@EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class)
|
||||||
|
// @TestPropertySource(locations = "classpath:application-integrationtest.properties")
|
||||||
|
@AutoConfigureTestDatabase
|
||||||
|
public class EmployeeRestControllerIntegrationTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MockMvc mvc;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeRepository repository;
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void resetDb() {
|
||||||
|
repository.deleteAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenValidInput_thenCreateEmployee() throws IOException, Exception {
|
||||||
|
Employee bob = new Employee("bob");
|
||||||
|
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(bob)));
|
||||||
|
|
||||||
|
List<Employee> found = repository.findAll();
|
||||||
|
assertThat(found).extracting(Employee::getName).containsOnly("bob");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmployees_whenGetEmployees_thenStatus200() throws Exception {
|
||||||
|
createTestEmployee("bob");
|
||||||
|
createTestEmployee("alex");
|
||||||
|
|
||||||
|
// @formatter:off
|
||||||
|
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))
|
||||||
|
.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
|
||||||
|
.andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
|
||||||
|
.andExpect(jsonPath("$[0].name", is("bob")))
|
||||||
|
.andExpect(jsonPath("$[1].name", is("alex")));
|
||||||
|
// @formatter:on
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
|
private void createTestEmployee(String name) {
|
||||||
|
Employee emp = new Employee(name);
|
||||||
|
repository.saveAndFlush(emp);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,132 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
import org.mockito.internal.verification.VerificationModeFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.TestConfiguration;
|
||||||
|
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import com.baeldung.boot.testing.Employee;
|
||||||
|
import com.baeldung.boot.testing.EmployeeRepository;
|
||||||
|
import com.baeldung.boot.testing.EmployeeService;
|
||||||
|
import com.baeldung.boot.testing.EmployeeServiceImpl;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
public class EmployeeServiceImplIntegrationTest {
|
||||||
|
|
||||||
|
@TestConfiguration
|
||||||
|
static class EmployeeServiceImplTestContextConfiguration {
|
||||||
|
@Bean
|
||||||
|
public EmployeeService employeeService() {
|
||||||
|
return new EmployeeServiceImpl();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeService employeeService;
|
||||||
|
|
||||||
|
@MockBean
|
||||||
|
private EmployeeRepository employeeRepository;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
Employee john = new Employee("john");
|
||||||
|
john.setId(11L);
|
||||||
|
|
||||||
|
Employee bob = new Employee("bob");
|
||||||
|
Employee alex = new Employee("alex");
|
||||||
|
|
||||||
|
List<Employee> allEmployees = Arrays.asList(john, bob, alex);
|
||||||
|
|
||||||
|
Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john);
|
||||||
|
Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex);
|
||||||
|
Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null);
|
||||||
|
Mockito.when(employeeRepository.findById(john.getId())).thenReturn(Optional.of(john));
|
||||||
|
Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees);
|
||||||
|
Mockito.when(employeeRepository.findById(-99L)).thenReturn(Optional.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenValidName_thenEmployeeShouldBeFound() {
|
||||||
|
String name = "alex";
|
||||||
|
Employee found = employeeService.getEmployeeByName(name);
|
||||||
|
|
||||||
|
assertThat(found.getName()).isEqualTo(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInValidName_thenEmployeeShouldNotBeFound() {
|
||||||
|
Employee fromDb = employeeService.getEmployeeByName("wrong_name");
|
||||||
|
assertThat(fromDb).isNull();
|
||||||
|
|
||||||
|
verifyFindByNameIsCalledOnce("wrong_name");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenValidName_thenEmployeeShouldExist() {
|
||||||
|
boolean doesEmployeeExist = employeeService.exists("john");
|
||||||
|
assertThat(doesEmployeeExist).isEqualTo(true);
|
||||||
|
|
||||||
|
verifyFindByNameIsCalledOnce("john");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNonExistingName_thenEmployeeShouldNotExist() {
|
||||||
|
boolean doesEmployeeExist = employeeService.exists("some_name");
|
||||||
|
assertThat(doesEmployeeExist).isEqualTo(false);
|
||||||
|
|
||||||
|
verifyFindByNameIsCalledOnce("some_name");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenValidId_thenEmployeeShouldBeFound() {
|
||||||
|
Employee fromDb = employeeService.getEmployeeById(11L);
|
||||||
|
assertThat(fromDb.getName()).isEqualTo("john");
|
||||||
|
|
||||||
|
verifyFindByIdIsCalledOnce();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInValidId_thenEmployeeShouldNotBeFound() {
|
||||||
|
Employee fromDb = employeeService.getEmployeeById(-99L);
|
||||||
|
verifyFindByIdIsCalledOnce();
|
||||||
|
assertThat(fromDb).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given3Employees_whengetAll_thenReturn3Records() {
|
||||||
|
Employee alex = new Employee("alex");
|
||||||
|
Employee john = new Employee("john");
|
||||||
|
Employee bob = new Employee("bob");
|
||||||
|
|
||||||
|
List<Employee> allEmployees = employeeService.getAllEmployees();
|
||||||
|
verifyFindAllEmployeesIsCalledOnce();
|
||||||
|
assertThat(allEmployees).hasSize(3).extracting(Employee::getName).contains(alex.getName(), john.getName(), bob.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void verifyFindByNameIsCalledOnce(String name) {
|
||||||
|
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findByName(name);
|
||||||
|
Mockito.reset(employeeRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void verifyFindByIdIsCalledOnce() {
|
||||||
|
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findById(Mockito.anyLong());
|
||||||
|
Mockito.reset(employeeRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void verifyFindAllEmployeesIsCalledOnce() {
|
||||||
|
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findAll();
|
||||||
|
Mockito.reset(employeeRepository);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.boot.testing;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
class JsonUtil {
|
||||||
|
static byte[] toJson(Object object) throws IOException {
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||||
|
return mapper.writeValueAsBytes(object);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.prevent.commandline.application.runner.execution;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.boot.CommandLineRunner;
|
||||||
|
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
|
||||||
|
import org.springframework.boot.test.mock.mockito.SpyBean;
|
||||||
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.ApplicationCommandLineRunnerApp;
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.TaskService;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@ContextConfiguration(classes = { ApplicationCommandLineRunnerApp.class },
|
||||||
|
initializers = ConfigDataApplicationContextInitializer.class)
|
||||||
|
public class LoadSpringContextIntegrationTest {
|
||||||
|
@SpyBean
|
||||||
|
TaskService taskService;
|
||||||
|
|
||||||
|
@SpyBean
|
||||||
|
CommandLineRunner commandLineRunner;
|
||||||
|
|
||||||
|
@SpyBean
|
||||||
|
ApplicationRunner applicationRunner;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenContextLoads_thenRunnersDoNotRun() throws Exception {
|
||||||
|
assertNotNull(taskService);
|
||||||
|
assertNotNull(commandLineRunner);
|
||||||
|
assertNotNull(applicationRunner);
|
||||||
|
|
||||||
|
verify(taskService, times(0)).execute(any());
|
||||||
|
verify(commandLineRunner, times(0)).run(any());
|
||||||
|
verify(applicationRunner, times(0)).run(any());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.prevent.commandline.application.runner.execution;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.mock.mockito.SpyBean;
|
||||||
|
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor;
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor;
|
||||||
|
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
class RunApplicationIntegrationTest {
|
||||||
|
@SpyBean
|
||||||
|
ApplicationRunnerTaskExecutor applicationRunnerTaskExecutor;
|
||||||
|
@SpyBean
|
||||||
|
CommandLineTaskExecutor commandLineTaskExecutor;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenContextLoads_thenRunnersRun() throws Exception {
|
||||||
|
verify(applicationRunnerTaskExecutor, times(1)).run(any());
|
||||||
|
verify(commandLineTaskExecutor, times(1)).run(any());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.prevent.commandline.application.runner.execution;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor;
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor;
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.TaskService;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@SpringBootTest
|
||||||
|
class RunApplicationWithTestProfileIntegrationTest {
|
||||||
|
@Autowired
|
||||||
|
private ApplicationContext context;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenContextLoads_thenRunnersAreNotLoaded() {
|
||||||
|
assertNotNull(context.getBean(TaskService.class));
|
||||||
|
assertThrows(NoSuchBeanDefinitionException.class,
|
||||||
|
() -> context.getBean(CommandLineTaskExecutor.class),
|
||||||
|
"CommandLineRunner should not be loaded during this integration test");
|
||||||
|
assertThrows(NoSuchBeanDefinitionException.class,
|
||||||
|
() -> context.getBean(ApplicationRunnerTaskExecutor.class),
|
||||||
|
"ApplicationRunner should not be loaded during this integration test");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.prevent.commandline.application.runner.execution;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor;
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor;
|
||||||
|
import com.baeldung.prevent.commandline.application.runner.execution.TaskService;
|
||||||
|
|
||||||
|
@SpringBootTest(properties = {
|
||||||
|
"command.line.runner.enabled=false",
|
||||||
|
"application.runner.enabled=false" })
|
||||||
|
class RunApplicationWithTestPropertiesIntegrationTest {
|
||||||
|
@Autowired
|
||||||
|
private ApplicationContext context;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenContextLoads_thenRunnersAreNotLoaded() {
|
||||||
|
assertNotNull(context.getBean(TaskService.class));
|
||||||
|
assertThrows(NoSuchBeanDefinitionException.class,
|
||||||
|
() -> context.getBean(CommandLineTaskExecutor.class),
|
||||||
|
"CommandLineRunner should not be loaded during this integration test");
|
||||||
|
assertThrows(NoSuchBeanDefinitionException.class,
|
||||||
|
() -> context.getBean(ApplicationRunnerTaskExecutor.class),
|
||||||
|
"ApplicationRunner should not be loaded during this integration test");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,4 @@
|
|||||||
|
spring.datasource.url=jdbc:mysql://localhost:3306/employee_int_test
|
||||||
|
spring.datasource.username=root
|
||||||
|
spring.datasource.password=root
|
||||||
|
|
@ -0,0 +1,2 @@
|
|||||||
|
# test properties
|
||||||
|
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
|
@ -0,0 +1,8 @@
|
|||||||
|
#embedded redis
|
||||||
|
spring.redis.host= localhost
|
||||||
|
spring.redis.port= 6370
|
||||||
|
# security
|
||||||
|
spring.security.user.name=john
|
||||||
|
spring.security.user.password=123
|
||||||
|
|
||||||
|
spring.main.allow-bean-definition-overriding=true
|
@ -0,0 +1,19 @@
|
|||||||
|
spring:
|
||||||
|
config:
|
||||||
|
activate:
|
||||||
|
on-profile: test
|
||||||
|
server:
|
||||||
|
address:
|
||||||
|
ip: 192.168.0.4
|
||||||
|
resources_path:
|
||||||
|
imgs: /etc/test/imgs
|
||||||
|
---
|
||||||
|
spring:
|
||||||
|
config:
|
||||||
|
activate:
|
||||||
|
on-profile: dev
|
||||||
|
server:
|
||||||
|
address:
|
||||||
|
ip: 192.168.0.5
|
||||||
|
resources_path:
|
||||||
|
imgs: /etc/dev/imgs
|
@ -0,0 +1,12 @@
|
|||||||
|
<configuration>
|
||||||
|
<include resource="/org/springframework/boot/logging/logback/base.xml"/>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
<root level="error">
|
||||||
|
<appender-ref ref="STDOUT"/>
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -0,0 +1,4 @@
|
|||||||
|
validate.propertiesMap.first=prop1
|
||||||
|
validate.propertiesMap.second=prop2
|
||||||
|
|
||||||
|
validate.mail_config.address=user1@test
|
@ -0,0 +1,6 @@
|
|||||||
|
server.address.ip=192.168.0.1
|
||||||
|
server.resources_path.imgs=/root/imgs
|
||||||
|
|
||||||
|
# default config
|
||||||
|
server.default.address.ip=192.168.0.2
|
||||||
|
server.default.resources_path.imgs=/root/def/imgs
|
@ -0,0 +1,10 @@
|
|||||||
|
# bandwidth
|
||||||
|
server.upload_speed=500MB
|
||||||
|
server.download_speed=10
|
||||||
|
|
||||||
|
# backup date
|
||||||
|
server.backup_day=1d
|
||||||
|
server.backup_hour=8
|
||||||
|
|
||||||
|
# custom converter
|
||||||
|
server.credentials=user,123
|
Loading…
x
Reference in New Issue
Block a user