Compare commits

..

5 Commits

Author SHA1 Message Date
Tom Hombergs
500ee0a04f ignored test because it cannot run on CI 2018-05-27 21:55:26 +02:00
Tom Hombergs
4d67dd44d0 fix 2018-05-27 21:10:15 +02:00
Tom Hombergs
a4d70d5835 Example application for structuring a Spring Boot app 2018-05-27 20:55:24 +02:00
Tom Hombergs
f2b83425ac inital checking for spring-boot-test example project 2018-05-20 20:38:28 +02:00
Tom Hombergs
f854262f80 changed package name 2018-03-18 22:44:54 +01:00
49 changed files with 961 additions and 200 deletions

View File

@@ -0,0 +1,11 @@
<component name="libraryTable">
<library name="Gradle: org.projectlombok:lombok:1.16.20">
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.projectlombok/lombok/1.16.20/ac76d9b956045631d1561a09289cbf472e077c01/lombok-1.16.20.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.projectlombok/lombok/1.16.20/69ebf81bb97bdb3c9581c171762bb4929cb5289c/lombok-1.16.20-sources.jar!/" />
</SOURCES>
</library>
</component>

13
.idea/modules/spring-boot-testing.iml generated Normal file
View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="spring-boot-testing" external.linked.project.path="$MODULE_DIR$/../../spring-boot/spring-boot-testing" external.root.project.path="$MODULE_DIR$/../../spring-boot/spring-boot-testing" external.system.id="GRADLE" external.system.module.group="reflectoring.io" external.system.module.version="0.0.1-SNAPSHOT" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$/../../spring-boot/spring-boot-testing">
<excludeFolder url="file://$MODULE_DIR$/../../spring-boot/spring-boot-testing/.gradle" />
<excludeFolder url="file://$MODULE_DIR$/../../spring-boot/spring-boot-testing/build" />
<excludeFolder url="file://$MODULE_DIR$/../../spring-boot/spring-boot-testing/out" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -1,11 +1,13 @@
# Creating a Consumer-Driven Contract with Feign and Pact # Testing a Spring Boot REST API Consumer against a Contract with Spring Cloud Contract
## Companion Blog Article ## Companion Blog Article
Read the [companion blog article](https://reflectoring.io/consumer-driven-contract-feign-pact/) to this repository. Read the [companion blog article](https://reflectoring.io/consumer-driven-contract-consumer-spring-cloud-contract/) to this repository.
## Getting Started ## Getting Started
* have a look at the [contract](/src/test/resources/contracts)
* have a look at the [feign client](/src/main/java/io/reflectoring/UserClient.java) * have a look at the [feign client](/src/main/java/io/reflectoring/UserClient.java)
* have a look at the [consumer test](/src/test/java/io/reflectoring/UserServiceConsumerTest.java) * have a look at the [consumer test](/src/test/java/io/reflectoring/UserClientTest.java)
* run `./gradlew build` to run all tests and create pact files into the folder `target/pacts` * run `./gradlew publishToMavenLocal` in the [producer project](../spring-cloud-contract-provider)
* run `./gradlew pactPublish` to publish the pact files to a Pact Broker (must specify Pact Broker location and credentials in `build.gradle`) to create a provider stubs
* run `./gradlew build` in this project to verify the feign client against the stub

View File

@@ -1,3 +1,5 @@
apply plugin: 'org.springframework.boot'
buildscript { buildscript {
repositories { repositories {
mavenLocal() mavenLocal()
@@ -8,13 +10,6 @@ buildscript {
} }
} }
plugins {
id "au.com.dius.pact" version "3.5.13"
}
apply plugin: 'org.springframework.boot'
version '1.0.0.SNAPSHOT'
repositories { repositories {
mavenLocal() mavenLocal()
@@ -30,12 +25,3 @@ dependencies {
testCompile("au.com.dius:pact-jvm-consumer-junit_2.11:3.5.2") testCompile("au.com.dius:pact-jvm-consumer-junit_2.11:3.5.2")
testCompile("org.springframework.boot:spring-boot-starter-test:${springboot_version}") testCompile("org.springframework.boot:spring-boot-starter-test:${springboot_version}")
} }
pact {
publish {
pactDirectory = 'target/pacts'
pactBrokerUrl = 'URL'
pactBrokerUsername = 'USERNAME'
pactBrokerPassword = 'PASSWORD'
}
}

View File

@@ -27,7 +27,7 @@ public class UserServiceConsumerTest {
@Autowired @Autowired
private UserClient userClient; private UserClient userClient;
@Pact(provider = "userservice", consumer = "userclient") @Pact(state = "provider accepts a new person", provider = "userservice", consumer = "userclient")
public RequestResponsePact createPersonPact(PactDslWithProvider builder) { public RequestResponsePact createPersonPact(PactDslWithProvider builder) {
return builder return builder
.given("provider accepts a new person") .given("provider accepts a new person")
@@ -42,19 +42,19 @@ public class UserServiceConsumerTest {
.toPact(); .toPact();
} }
@Pact(provider = "userservice", consumer = "userclient") @Pact(state = "person 42 exists", provider = "userservice", consumer = "userclient")
public RequestResponsePact updatePersonPact(PactDslWithProvider builder) { public RequestResponsePact updatePersonPact(PactDslWithProvider builder) {
return builder return builder
.given("person 42 exists") .given("person 42 exists")
.uponReceiving("a request to PUT a person") .uponReceiving("a request to PUT a person")
.path("/user-service/users/42") .path("/user-service/users/42")
.method("PUT") .method("PUT")
.willRespondWith() .willRespondWith()
.status(200) .status(200)
.matchHeader("Content-Type", "application/json") .matchHeader("Content-Type", "application/json")
.body(new PactDslJsonBody() .body(new PactDslJsonBody()
.stringType("firstName", "Zaphod") .stringType("firstName", "Zaphod")
.stringType("lastName", "Beeblebrox")) .stringType("lastName", "Beeblebrox"))
.toPact(); .toPact();
} }

View File

@@ -0,0 +1,11 @@
spring:
datasource:
url: jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
driverClassName: org.h2.Driver
username: sa
password:
h2:
console:
enabled: true
logging.level.org.hibernate.SQL: OFF

View File

@@ -26,7 +26,7 @@ dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa') compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.boot:spring-boot-starter-web')
compile('com.h2database:h2:1.4.196') compile('com.h2database:h2:1.4.196')
testCompile('au.com.dius:pact-jvm-provider-spring_2.12:3.5.11') testCompile('au.com.dius:pact-jvm-provider-spring_2.12:3.5.16')
testCompile('junit:junit:4.12') testCompile('junit:junit:4.12')
testCompile('org.springframework.boot:spring-boot-starter-test') testCompile('org.springframework.boot:spring-boot-starter-test')
} }

View File

@@ -1,4 +1,4 @@
package com.example.demo; package io.reflectoring;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@@ -1,4 +1,4 @@
package com.example.demo; package io.reflectoring;
public class IdObject { public class IdObject {

View File

@@ -1,4 +1,4 @@
package com.example.demo; package io.reflectoring;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;

View File

@@ -1,7 +1,6 @@
package com.example.demo; package io.reflectoring;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;

View File

@@ -1,4 +1,4 @@
package com.example.demo; package io.reflectoring;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;

View File

@@ -1,7 +0,0 @@
spring.datasource.url=jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
logging.level.org.hibernate.SQL=OFF

View File

@@ -1,4 +1,4 @@
package com.example.demo; package io.reflectoring;
import au.com.dius.pact.provider.junit.Provider; import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.State; import au.com.dius.pact.provider.junit.State;
@@ -7,6 +7,8 @@ import au.com.dius.pact.provider.junit.target.HttpTarget;
import au.com.dius.pact.provider.junit.target.Target; import au.com.dius.pact.provider.junit.target.Target;
import au.com.dius.pact.provider.junit.target.TestTarget; import au.com.dius.pact.provider.junit.target.TestTarget;
import au.com.dius.pact.provider.spring.SpringRestPactRunner; import au.com.dius.pact.provider.spring.SpringRestPactRunner;
import io.reflectoring.User;
import io.reflectoring.UserRepository;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.MockBean;

View File

@@ -17,6 +17,7 @@ include 'spring-boot:rabbitmq-event-brokering'
include 'spring-boot:modular:security-module' include 'spring-boot:modular:security-module'
include 'spring-boot:modular:booking-module' include 'spring-boot:modular:booking-module'
include 'spring-boot:modular:application' include 'spring-boot:modular:application'
include 'spring-boot:spring-boot-testing'
include 'junit:conditions' include 'junit:conditions'

View File

@@ -0,0 +1,27 @@
.gradle
/build/
!gradle/wrapper/gradle-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
/out/
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

View File

@@ -0,0 +1,34 @@
buildscript {
ext {
springBootVersion = '2.0.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'reflectoring.io'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web')
compileOnly('org.projectlombok:lombok')
runtime('com.h2database:h2')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile 'org.junit.jupiter:junit-jupiter-engine:5.2.0'
}

172
spring-boot/spring-boot-testing/gradlew vendored Normal file
View File

@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
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
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
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
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1 @@
rootProject.name = 'spring-boot-testing'

View File

@@ -0,0 +1,13 @@
package io.reflectoring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -0,0 +1,32 @@
package io.reflectoring.booking;
import io.reflectoring.booking.business.BookingService;
import io.reflectoring.booking.data.BookingRepository;
import io.reflectoring.customer.CustomerConfiguration;
import io.reflectoring.customer.data.CustomerRepository;
import io.reflectoring.flight.FlightConfiguration;
import io.reflectoring.flight.data.FlightService;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootConfiguration
@Import({CustomerConfiguration.class, FlightConfiguration.class})
@EnableAutoConfiguration
@ComponentScan
public class BookingConfiguration {
@Bean
public BookingService bookingService(
BookingRepository bookingRepository,
CustomerRepository customerRepository,
FlightService flightService) {
return new BookingService(bookingRepository, customerRepository, flightService);
}
}

View File

@@ -0,0 +1,52 @@
package io.reflectoring.booking.business;
import java.util.Optional;
import io.reflectoring.booking.data.Booking;
import io.reflectoring.booking.data.BookingRepository;
import io.reflectoring.customer.data.Customer;
import io.reflectoring.customer.data.CustomerRepository;
import io.reflectoring.flight.data.Flight;
import io.reflectoring.flight.data.FlightService;
public class BookingService {
private BookingRepository bookingRepository;
private CustomerRepository customerRepository;
FlightService flightService;
public BookingService(
BookingRepository bookingRepository,
CustomerRepository customerRepository,
FlightService flightService) {
this.bookingRepository = bookingRepository;
this.customerRepository = customerRepository;
this.flightService = flightService;
}
/**
* Books the given flight for the given customer.
*/
public Booking bookFlight(Long customerId, String flightNumber) {
Optional<Customer> customer = customerRepository.findById(customerId);
if (!customer.isPresent()) {
throw new CustomerDoesNotExistException(customerId);
}
Optional<Flight> flight = flightService.findFlight(flightNumber);
if (!flight.isPresent()) {
throw new FlightDoesNotExistException(flightNumber);
}
Booking booking = Booking.builder()
.customer(customer.get())
.flightNumber(flight.get().getFlightNumber())
.build();
return this.bookingRepository.save(booking);
}
}

View File

@@ -0,0 +1,9 @@
package io.reflectoring.booking.business;
class CustomerDoesNotExistException extends RuntimeException {
CustomerDoesNotExistException(Long customerId) {
super(String.format("A customer with ID '%d' doesn't exist!", customerId));
}
}

View File

@@ -0,0 +1,9 @@
package io.reflectoring.booking.business;
class FlightDoesNotExistException extends RuntimeException {
FlightDoesNotExistException(String flightNumber) {
super(String.format("A flight with ID '%d' doesn't exist!", flightNumber));
}
}

View File

@@ -0,0 +1,25 @@
package io.reflectoring.booking.data;
import javax.persistence.*;
import io.reflectoring.customer.data.Customer;
import io.reflectoring.flight.data.Flight;
import lombok.Builder;
import lombok.Data;
@Entity
@Data
@Builder
public class Booking {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Customer customer;
@Column
private String flightNumber;
}

View File

@@ -0,0 +1,6 @@
package io.reflectoring.booking.data;
import org.springframework.data.repository.CrudRepository;
public interface BookingRepository extends CrudRepository<Booking, Long> {
}

View File

@@ -0,0 +1,30 @@
package io.reflectoring.booking.web;
import io.reflectoring.booking.business.BookingService;
import io.reflectoring.booking.data.Booking;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookingController {
private BookingService bookingService;
public BookingController(BookingService bookingService) {
this.bookingService = bookingService;
}
@PostMapping("/booking")
public ResponseEntity<BookingResultResource> bookFlight(
@RequestParam("customerId") Long customerId,
@RequestParam("flightNumber") String flightNumber) {
Booking booking = bookingService.bookFlight(customerId, flightNumber);
BookingResultResource bookingResult = BookingResultResource.builder()
.success(true)
.build();
return ResponseEntity.ok(bookingResult);
}
}

View File

@@ -0,0 +1,12 @@
package io.reflectoring.booking.web;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class BookingResultResource {
private boolean success;
}

View File

@@ -0,0 +1,14 @@
package io.reflectoring.customer;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public class CustomerConfiguration {
}

View File

@@ -0,0 +1,21 @@
package io.reflectoring.customer.data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.*;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Customer {
@Id
@GeneratedValue
private Long id;
private String name;
}

View File

@@ -0,0 +1,11 @@
package io.reflectoring.customer.data;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByName(String name);
}

View File

@@ -0,0 +1,23 @@
package io.reflectoring.flight;
import io.reflectoring.flight.data.FlightService;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableScheduling
@ComponentScan
public class FlightConfiguration {
@Bean
public FlightService flightService(){
return new FlightService();
}
}

View File

@@ -0,0 +1,14 @@
package io.reflectoring.flight.data;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class Flight {
private String flightNumber;
private String airline;
}

View File

@@ -0,0 +1,14 @@
package io.reflectoring.flight.data;
import java.util.Optional;
public class FlightService {
public Optional<Flight> findFlight(String flightNumber) {
return Optional.of(Flight.builder()
.airline("Oceanic")
.flightNumber("815")
.build());
}
}

View File

@@ -0,0 +1,16 @@
package io.reflectoring;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@SpringBootTest
class ApplicationTests {
@Test
void applicationContextLoads() {
}
}

View File

@@ -0,0 +1,32 @@
package io.reflectoring.booking;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = BookingConfiguration.class)
class BookingConfigurationTest {
@Autowired
private ApplicationContext applicationContext;
@BeforeEach
void printApplicationContext() {
Arrays.stream(applicationContext.getBeanDefinitionNames())
.map(name -> applicationContext.getBean(name).getClass().getName())
.sorted()
.forEach(System.out::println);
}
@Test
void bookingConfigurationLoads() {
}
}

View File

@@ -0,0 +1,49 @@
package io.reflectoring.booking;
import io.reflectoring.customer.data.Customer;
import io.reflectoring.customer.data.CustomerRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@SpringBootTest
class BookingIntegrationTest {
@Autowired
private WebApplicationContext applicationContext;
@Autowired
private CustomerRepository customerRepository;
private MockMvc mockMvc;
@BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(applicationContext)
.build();
}
@Test
void bookFlightReturnsHttpStatusOk() throws Exception {
this.customerRepository.save(Customer.builder()
.name("Hurley")
.build());
this.mockMvc.perform(
post("/booking")
.param("customerId", "1")
.param("flightNumber", "Oceanic 815"))
.andExpect(status().isOk());
}
}

View File

@@ -0,0 +1,67 @@
package io.reflectoring.booking.business;
import java.util.Optional;
import io.reflectoring.booking.data.Booking;
import io.reflectoring.booking.data.BookingRepository;
import io.reflectoring.customer.data.Customer;
import io.reflectoring.customer.data.CustomerRepository;
import io.reflectoring.flight.data.Flight;
import io.reflectoring.flight.data.FlightService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class BookingServiceTest {
private CustomerRepository customerRepository = Mockito.mock(CustomerRepository.class);
private FlightService flightService = Mockito.mock(FlightService.class);
private BookingRepository bookingRepository = Mockito.mock(BookingRepository.class);
private BookingService bookingService;
@BeforeEach
void setup() {
this.bookingService = new BookingService(bookingRepository, customerRepository, flightService);
}
@Test
void bookFlightReturnsBooking() {
when(customerRepository.findById(42L)).thenReturn(customer());
when(flightService.findFlight("Oceanic 815")).thenReturn(flight());
when(bookingRepository.save(eq(booking()))).thenReturn(booking());
Booking booking = bookingService.bookFlight(42L, "Oceanic 815");
assertThat(booking).isNotNull();
verify(bookingRepository).save(eq(booking));
}
private Optional<Flight> flight() {
return Optional.of(Flight.builder()
.flightNumber("Oceanic 815")
.airline("Oceanic")
.build());
}
private Booking booking() {
return Booking.builder()
.flightNumber("Oceanic 815")
.customer(customer().get())
.build();
}
private Optional<Customer> customer() {
return Optional.of(Customer.builder()
.id(42L)
.name("Hurley")
.build());
}
}

View File

@@ -0,0 +1,67 @@
package io.reflectoring.booking.web;
import java.util.Arrays;
import io.reflectoring.booking.business.BookingService;
import io.reflectoring.booking.data.Booking;
import io.reflectoring.customer.data.Customer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = BookingController.class)
class BookingControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ApplicationContext applicationContext;
@MockBean
private BookingService bookingService;
@BeforeEach
void printApplicationContext() {
Arrays.stream(applicationContext.getBeanDefinitionNames())
.map(name -> applicationContext.getBean(name).getClass().getName())
.sorted()
.forEach(System.out::println);
}
@Test
void bookFlightReturnsHttpStatusOk() throws Exception {
when(bookingService.bookFlight(eq(42L), eq("Oceanic 815")))
.thenReturn(expectedBooking());
mockMvc.perform(
post("/booking")
.param("customerId", "42")
.param("flightNumber", "Oceanic 815"))
.andExpect(status().isOk());
}
private Booking expectedBooking() {
return Booking.builder()
.customer(Customer.builder()
.id(42L)
.name("Zaphod")
.build())
.flightNumber("Oceanic 815")
.build();
}
}

View File

@@ -0,0 +1,16 @@
package io.reflectoring.customer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = CustomerConfiguration.class)
class CustomerConfigurationTest {
@Test
void bookingConfigurationLoads() {
}
}

View File

@@ -0,0 +1,44 @@
package io.reflectoring.customer.data;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SpringExtension.class)
@DataJpaTest
class CustomerRepositoryTest {
@Autowired
private CustomerRepository repository;
@Autowired
private ApplicationContext applicationContext;
@BeforeEach
void printApplicationContext() {
Arrays.stream(applicationContext.getBeanDefinitionNames())
.map(name -> applicationContext.getBean(name).getClass().getName())
.sorted()
.forEach(System.out::println);
}
@Test
void findsByName() {
Customer customer = Customer.builder()
.name("Hurley")
.build();
repository.save(customer);
List<Customer> foundCustomers = repository.findByName("Hurley");
assertThat(foundCustomers).hasSize(1);
}
}

View File

@@ -0,0 +1,4 @@
package io.reflectoring.flight;
public class FlightMockConfiguration {
}

View File

@@ -1,27 +0,0 @@
package userservice
import org.springframework.cloud.contract.spec.Contract
Contract.make {
description("When a POST request with a User is made, the created user's ID is returned")
request {
method 'POST'
url '/user-service/users'
body(
firstName: "Arthur",
lastName: "Dent"
)
headers {
contentType(applicationJson())
}
}
response {
status 201
body(
id: 42
)
headers {
contentType(applicationJson())
}
}
}

View File

@@ -1,27 +0,0 @@
package userservice
import org.springframework.cloud.contract.spec.Contract
Contract.make {
description("When a PUT request with a User is made, the updated user's ID is returned")
request {
method 'PUT'
url '/user-service/users/42'
body(
firstName: "Arthur",
lastName: "Dent"
)
headers {
contentType(applicationJson())
}
}
response {
status 200
body(
id: 42
)
headers {
contentType(applicationJson())
}
}
}

View File

@@ -1,26 +0,0 @@
{
"id" : "90f75764-c4c3-4e8c-8bdb-876d31a28fec",
"request" : {
"url" : "/user-service/users",
"method" : "POST",
"headers" : {
"Content-Type" : {
"equalTo" : "application/json"
}
},
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.['lastName'] == 'Dent')]"
}, {
"matchesJsonPath" : "$[?(@.['firstName'] == 'Arthur')]"
} ]
},
"response" : {
"status" : 201,
"body" : "{\"id\":42}",
"headers" : {
"Content-Type" : "application/json;charset=UTF-8"
},
"transformers" : [ "response-template" ]
},
"uuid" : "90f75764-c4c3-4e8c-8bdb-876d31a28fec"
}

View File

@@ -1,23 +0,0 @@
{
"id" : "ca60467b-7665-4f28-b801-73d8af8125b1",
"request" : {
"url" : "/user-service/users/42",
"method" : "PUT",
"headers" : {
"Content-Type" : {
"equalTo" : "application/json"
}
},
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.['lastName'] == 'Beeblebrox')]"
}, {
"matchesJsonPath" : "$[?(@.['firstName'] == 'Zaphod')]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\"firstName\":\"Zaphod\",\"lastName\":\"Beeblebrox\"}",
"transformers" : [ "response-template" ]
},
"uuid" : "ca60467b-7665-4f28-b801-73d8af8125b1"
}

View File

@@ -1,26 +0,0 @@
{
"id" : "24699071-7724-459a-9e15-6d0340082230",
"request" : {
"url" : "/user-service/users",
"method" : "POST",
"headers" : {
"Content-Type" : {
"matches" : "application/json.*"
}
},
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.['lastName'] == 'Dent')]"
}, {
"matchesJsonPath" : "$[?(@.['firstName'] == 'Arthur')]"
} ]
},
"response" : {
"status" : 201,
"body" : "{\"id\":42}",
"headers" : {
"Content-Type" : "application/json"
},
"transformers" : [ "response-template" ]
},
"uuid" : "24699071-7724-459a-9e15-6d0340082230"
}

View File

@@ -1,26 +0,0 @@
{
"id" : "a74535f2-8b30-44e5-ad3c-074c8cc51ee0",
"request" : {
"url" : "/user-service/users/42",
"method" : "PUT",
"headers" : {
"Content-Type" : {
"matches" : "application/json.*"
}
},
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.['lastName'] == 'Dent')]"
}, {
"matchesJsonPath" : "$[?(@.['firstName'] == 'Arthur')]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\"id\":42}",
"headers" : {
"Content-Type" : "application/json"
},
"transformers" : [ "response-template" ]
},
"uuid" : "a74535f2-8b30-44e5-ad3c-074c8cc51ee0"
}