SlideShare a Scribd company logo
93 © VictorRentea.ro
a training by
Integration Testing
with Spring
victor.rentea@gmail.com VictorRentea.ro @victorrentea
Victor Rentea
Blog, Talks, Goodies on
VictorRentea.ro
Independent Trainer
dedicated for companies / masterclasses for individuals
Founder of
Bucharest Software Craftsmanship Community
Java Champion
❤️ Simple Design, Refactoring, Unit Testing ❤️
victorrentea.ro/community
Technical Training
400 days
(100+ online)
2000 devs
8 years
Training for you or your company: VictorRentea.ro
40 companies
Posting
Good Stuff on:
Hibernate
Spring Functional Prog
Java Performance
Reactive
Design Patterns
DDD
Clean Code
Refactoring
Unit Testing
TDD
any
lang
@victorrentea
96 © VictorRentea.ro
a training by
files
databases
queues
web services
Integration Tests
Failed Test Tolerance
If your test talks to and it fails,
is it a bug?
Probably not!😏
I hope not! 🙏
Tests failed
occasionally
some months after...
97 © VictorRentea.ro
a training by
Unit Tests
Integration
Deep
many layers
Fragile
DB, REST APIs, files
Fast
eg. 100 tests/sec
Slow
app startup,
network
... or Slow
in-mem DB, Spring,
Docker
failure ➔ maybe a bug
failure ➔ bug
Tiny
fine-grained
extensive mocks
98 © VictorRentea.ro
a training by
Zero Tolerance for Failed Tests
99 © VictorRentea.ro
a training by
🚨 USB device connected to Jenkins
100 © VictorRentea.ro
a training by
Let's Test a Search
Search Product
Name:
Supplier: IKEA
Search
...
DEV DB
eg Oracle
H2 in-memory
H2 standalone
DB in Docker
eg Oracle
102 © VictorRentea.ro
a training by
CODE
103 © VictorRentea.ro
a training by
@ActiveProfile("db-mem")
Toggle @Component, @Bean or @Configuration
Overrides properties with application-db-mem.properties
107 © VictorRentea.ro
a training by
Used to debug test
dependencies
Cleanup After Test
+10-60 wasted seconds
Spring
Don't push it to Jenkins!
@DirtiesContext
or
Manually
Before
111 © VictorRentea.ro
a training by
Isolated Repository Tests
@SpringBootTest
@RunWith(SpringRunner.class) // if on JUnit 4
public class TrainingServiceTest {
@Autowired
private TrainingRepo repo;
@Before/@BeforeEach
public void checkEmptyDatabase() {
assertThat(repo.findAll()).isEmpty();
}
@Test
public void getAll() {
...
repo.save(entity);
var results = repo.search(...);
assertEquals(...);
}
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
Safest but wastes time
Use For: debugging
repo.deleteAll(); ... // others.deleteAll()… // in FK order
@Transactional Run each test in a Transaction,
rolled back after each test.
Use For: Relational DBs
In Large Apps:
Check that the state is clean
Manual Cleanup
Use For: non-transacted resources (eg files, nosql)
112 © VictorRentea.ro
a training by
If every test class is @Transactional
Can I still have problems?
YES
Intermediate COMMITs
aka nested transaction
@Transactional(REQUIRES_NEW)
113 © VictorRentea.ro
a training by
Inserting Test Data
repo.save()
in @Test
in @BeforeEach
in superclass
in @RegisterExtension (JUnit5)
Insert via @Profile
A Spring bean persisting data at app startup
src/test/resources/data.sql
(auto-inserted after src/test/resources/schema.sql creation)
@Sql
CascadeType.PERSIST
helps A LOT !
114 © VictorRentea.ro
a training by
Running SQL Scripts
@Sql
@Sql("data.sql")
@Sql({"schema.sql", "data.sql"})
On method or class
@SqlMergeMode
TestClass.testMethod.sql
before or after @Test
in the same transaction
115 © VictorRentea.ro
a training by
What DB to use in Tests
in-memory H2
(create schema via Hibernate)
Same DB in Local Docker
(create schema via scripts)
Personal Schema on Physical DB
(eg. REGLISS_VICTOR)
Shared Test Schema on Physical DB Legacy 500+ tables schemas
For PL/SQL, native features
For JPA + native standard SQL
116 © VictorRentea.ro
a training by
Invest hours, days, weeks
to
Make Your Test run on CI
117 © VictorRentea.ro
a training by
Assertions.*
assertThat(scoreStr).isEqualTo("Game won");
assertThat(list).anyMatch(e -> e.getX() == 1);
.doesNotContain(2);
.containsExactlyInAnyOrder(1,2,3);
.isEmpty();
assertThatThrownBy(() -> prod())
.hasMessageContaining("address");
+50 more
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</dependency>
+60 more
Actual>Expected
Expected empty but was: <list.toString()>
Expressive Failure Message:
Testing Collections
Exceptions:
assertThat(list.stream().map(...))
118 © VictorRentea.ro
a training by
@txn
Feature: Records Search
Background:
Given Supplier "X" exists
Scenario Outline: Product Search
Given One product exists
And That product has name "<productName>"
When The search criteria name is "<searchName>"
Then That product is returned by search: "<returned>"
Examples:
| productName | searchName | returned |
| a | X | false |
| a | a | true |
Gherkin Language
wasted effort
if business never sees it
*
≈ @Before
= Separate transaction / test
.feature
119 © VictorRentea.ro
a training by
120 © VictorRentea.ro
a training by
@Bean
@Mock
121 © VictorRentea.ro
a training by
@Bean
@Mock
Replaces that bean with a Mockito Mock
Auto-reset() after each @Test
123 © VictorRentea.ro
a training by
Application Context is Reused
Starting Spring is slow.
Pro Tip:
Maximize Reuse
by test classes with the same:
@ActiveProfiles
@MockBean set
custom properties
locations= .xml
config classes= .class
more
124 © VictorRentea.ro
a training by
Faster Spring Tests
1. Tune JVM: -ea -noverify -mx2048m -XX:TieredStopAtLevel=1
Debugging Test Context reuse: logging.level.org.springframework.test.context.cache=DEBUG
4. Reuse Contexts: reduce no of Spring Banners on Jenkins
6. Disable/Limit Auto-Configuration
2. Lazy-Load only Tested Beans: spring.main.lazy-initialization=true
3. Disable Web: @SpringBootTest(webEnvironment = NONE)
https://stackoverflow.com/a/49663075
= +30 sec test run time
5. Run in parallel
125 © VictorRentea.ro
a training by
Reusing Test Context
@SpringBootTest
@Transactional
@ActiveProfiles({"db-mem", "test"})
public abstract class SpringTestBase {
@MockBean
protected FileRepo fileRepoMock;
... all @MockBeans ever needed
}
@ActiveProfiles("db-mem")
public class FeedProcessorWithMockTest
extends SpringTestBase {
@MockBean
when(fileRepoMock).then...
}
nothing requiring
dedicated context
126 © VictorRentea.ro
a training by
WireMock
127 © VictorRentea.ro
a training by
WireMock.stubFor(get(urlEqualTo("/some/thing"))
.withHeader("Accept", equalTo("text/xml"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("[{"id":12, "value":"WireMock"}]")));
B) Programmatically
{
"request": {
"method": "GET",
"url": "/some/thing"
},
"response": {
"status": 200,
"body": "Hello WireMock!",
"headers": {
"Content-Type": "text/plain"
}
}
}
A) via .json config files:
Templatize content
from a .json file on disk
Record them
from real systems
http://wiremock.org/docs/running-standalone/
WireMock
138 © VictorRentea.ro
a training by
My Application
SafetyClient
@MockBean
In-memory DB
(H2)
ProductRepo
Remote Sever
Real DB
@Transactional
WireMock
Local Docker
Real DB
.feature
What We've Covered
@DirtiesContext
ProductService
@Transactional
139 © VictorRentea.ro
a training by
files
databases
queues
web services
Integration Tests
140 © VictorRentea.ro
a training by
Unit Tests
Integration
Deep
many layers
Fast
eg. 100 tests/sec
Slow
app startup,
network
... or Slow
in-mem DB, Spring,
Docker
Tiny
fine-grained
extensive mocks
Fragile
DB, REST APIs, files
Company Training:
victorrentea@gmail.com
Training for You:
victorrentea.teachable.com
Thank You!
@victorrentea
Blog, Talks, Curricula:
victorrentea.ro

More Related Content

PPTX
Functional Patterns with Java8 @Bucharest Java User Group
PDF
Don't Be Mocked by your Mocks - Best Practices using Mocks
PDF
The Art of Unit Testing - Towards a Testable Design
PPTX
Clean Pragmatic Architecture - Avoiding a Monolith
PPTX
Clean Code
PDF
Unit Testing like a Pro - The Circle of Purity
PPTX
The Art of Clean code
PDF
Clean Lambdas & Streams in Java8
Functional Patterns with Java8 @Bucharest Java User Group
Don't Be Mocked by your Mocks - Best Practices using Mocks
The Art of Unit Testing - Towards a Testable Design
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Code
Unit Testing like a Pro - The Circle of Purity
The Art of Clean code
Clean Lambdas & Streams in Java8

What's hot (20)

PDF
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
PDF
The Proxy Fairy, and The Magic of Spring Framework
PPTX
The tests are trying to tell you something@VoxxedBucharest.pptx
PPTX
Clean Code - The Next Chapter
PDF
Clean pragmatic architecture @ devflix
PDF
Clean architecture - Protecting the Domain
PDF
Profiling your Java Application
PDF
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
PDF
Tech Talk #5 : Code Analysis SonarQube - Lương Trọng Nghĩa
PDF
Spring Meetup Paris - Back to the basics of Spring (Boot)
PPT
PPTX
Whitebox testing of Spring Boot applications
PPT
Ionic Framework
PPTX
Unit Testing And Mocking
PPTX
ORM을 활용할 경우의 설계, 개발 과정
PDF
Java 8 Workshop
PDF
Clean code
PPTX
JUnit- A Unit Testing Framework
PPT
Spring Core
PPTX
Clean code
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
The Proxy Fairy, and The Magic of Spring Framework
The tests are trying to tell you something@VoxxedBucharest.pptx
Clean Code - The Next Chapter
Clean pragmatic architecture @ devflix
Clean architecture - Protecting the Domain
Profiling your Java Application
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Tech Talk #5 : Code Analysis SonarQube - Lương Trọng Nghĩa
Spring Meetup Paris - Back to the basics of Spring (Boot)
Whitebox testing of Spring Boot applications
Ionic Framework
Unit Testing And Mocking
ORM을 활용할 경우의 설계, 개발 과정
Java 8 Workshop
Clean code
JUnit- A Unit Testing Framework
Spring Core
Clean code
Ad

Similar to Integration testing with spring @snow one (20)

PDF
Integration testing with spring @JAX Mainz
PDF
Testing Microservices @DevoxxBE 23.pdf
PPT
Test Drive Development in Ruby On Rails
PDF
Scala, Functional Programming and Team Productivity
PPT
Intro to Ruby on Rails
PPTX
Eclipse MicroProfile: Accelerating the adoption of Java Microservices
PPTX
Understanding JavaScript Testing
PPTX
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
PPTX
Anatomy of a Build Pipeline
DOCX
Ravindra Kumar
PDF
Testing Your Application On Google App Engine
PDF
Testing your application on Google App Engine
PDF
Cypress Automation : Increase Reusability with Custom Commands
PPTX
Automated Acceptance Tests & Tool choice
PPTX
Codeception
PDF
MicroProfile Devoxx.us
PDF
Leveling Up With Unit Testing - LonghornPHP 2022
PPT
Unit Testing Documentum Foundation Classes Code
PDF
Test ng for testers
PDF
Testing Legacy Rails Apps
Integration testing with spring @JAX Mainz
Testing Microservices @DevoxxBE 23.pdf
Test Drive Development in Ruby On Rails
Scala, Functional Programming and Team Productivity
Intro to Ruby on Rails
Eclipse MicroProfile: Accelerating the adoption of Java Microservices
Understanding JavaScript Testing
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
Anatomy of a Build Pipeline
Ravindra Kumar
Testing Your Application On Google App Engine
Testing your application on Google App Engine
Cypress Automation : Increase Reusability with Custom Commands
Automated Acceptance Tests & Tool choice
Codeception
MicroProfile Devoxx.us
Leveling Up With Unit Testing - LonghornPHP 2022
Unit Testing Documentum Foundation Classes Code
Test ng for testers
Testing Legacy Rails Apps
Ad

More from Victor Rentea (20)

PDF
Top REST API Desgin Pitfalls @ Devoxx 2024
PDF
The Joy of Testing - Deep Dive @ Devoxx Belgium 2024
PDF
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
PDF
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
PDF
Microservice Resilience Patterns @VoxxedCern'24
PDF
Distributed Consistency.pdf
PPTX
From Web to Flux @DevoxxBE 2023.pptx
PPTX
Test-Driven Design Insights@DevoxxBE 2023.pptx
PPTX
OAuth in the Wild
PPTX
Vertical Slicing Architectures
PDF
Software Craftsmanship @Code Camp Festival 2022.pdf
PDF
Unit testing - 9 design hints
PPTX
Extreme Professionalism - Software Craftsmanship
PDF
Refactoring blockers and code smells @jNation 2021
PDF
Hibernate and Spring - Unleash the Magic
PDF
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
PDF
Pure functions and immutable objects @dev nexus 2021
PDF
TDD Mantra
PDF
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
PDF
Pure Functions and Immutable Objects
Top REST API Desgin Pitfalls @ Devoxx 2024
The Joy of Testing - Deep Dive @ Devoxx Belgium 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Microservice Resilience Patterns @VoxxedCern'24
Distributed Consistency.pdf
From Web to Flux @DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
OAuth in the Wild
Vertical Slicing Architectures
Software Craftsmanship @Code Camp Festival 2022.pdf
Unit testing - 9 design hints
Extreme Professionalism - Software Craftsmanship
Refactoring blockers and code smells @jNation 2021
Hibernate and Spring - Unleash the Magic
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
Pure functions and immutable objects @dev nexus 2021
TDD Mantra
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Pure Functions and Immutable Objects

Recently uploaded (20)

PPTX
history of c programming in notes for students .pptx
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
L1 - Introduction to python Backend.pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
Digital Strategies for Manufacturing Companies
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
top salesforce developer skills in 2025.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
history of c programming in notes for students .pptx
Which alternative to Crystal Reports is best for small or large businesses.pdf
L1 - Introduction to python Backend.pptx
wealthsignaloriginal-com-DS-text-... (1).pdf
How to Choose the Right IT Partner for Your Business in Malaysia
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
ai tools demonstartion for schools and inter college
Digital Strategies for Manufacturing Companies
CHAPTER 2 - PM Management and IT Context
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Adobe Illustrator 28.6 Crack My Vision of Vector Design
VVF-Customer-Presentation2025-Ver1.9.pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
2025 Textile ERP Trends: SAP, Odoo & Oracle
top salesforce developer skills in 2025.pdf
Odoo Companies in India – Driving Business Transformation.pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...

Integration testing with spring @snow one

  • 1. 93 © VictorRentea.ro a training by Integration Testing with Spring victor.rentea@gmail.com VictorRentea.ro @victorrentea
  • 2. Victor Rentea Blog, Talks, Goodies on VictorRentea.ro Independent Trainer dedicated for companies / masterclasses for individuals Founder of Bucharest Software Craftsmanship Community Java Champion ❤️ Simple Design, Refactoring, Unit Testing ❤️ victorrentea.ro/community
  • 3. Technical Training 400 days (100+ online) 2000 devs 8 years Training for you or your company: VictorRentea.ro 40 companies Posting Good Stuff on: Hibernate Spring Functional Prog Java Performance Reactive Design Patterns DDD Clean Code Refactoring Unit Testing TDD any lang @victorrentea
  • 4. 96 © VictorRentea.ro a training by files databases queues web services Integration Tests Failed Test Tolerance If your test talks to and it fails, is it a bug? Probably not!😏 I hope not! 🙏 Tests failed occasionally some months after...
  • 5. 97 © VictorRentea.ro a training by Unit Tests Integration Deep many layers Fragile DB, REST APIs, files Fast eg. 100 tests/sec Slow app startup, network ... or Slow in-mem DB, Spring, Docker failure ➔ maybe a bug failure ➔ bug Tiny fine-grained extensive mocks
  • 6. 98 © VictorRentea.ro a training by Zero Tolerance for Failed Tests
  • 7. 99 © VictorRentea.ro a training by 🚨 USB device connected to Jenkins
  • 8. 100 © VictorRentea.ro a training by Let's Test a Search Search Product Name: Supplier: IKEA Search ... DEV DB eg Oracle H2 in-memory H2 standalone DB in Docker eg Oracle
  • 9. 102 © VictorRentea.ro a training by CODE
  • 10. 103 © VictorRentea.ro a training by @ActiveProfile("db-mem") Toggle @Component, @Bean or @Configuration Overrides properties with application-db-mem.properties
  • 11. 107 © VictorRentea.ro a training by Used to debug test dependencies Cleanup After Test +10-60 wasted seconds Spring Don't push it to Jenkins! @DirtiesContext or Manually Before
  • 12. 111 © VictorRentea.ro a training by Isolated Repository Tests @SpringBootTest @RunWith(SpringRunner.class) // if on JUnit 4 public class TrainingServiceTest { @Autowired private TrainingRepo repo; @Before/@BeforeEach public void checkEmptyDatabase() { assertThat(repo.findAll()).isEmpty(); } @Test public void getAll() { ... repo.save(entity); var results = repo.search(...); assertEquals(...); } @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) Safest but wastes time Use For: debugging repo.deleteAll(); ... // others.deleteAll()… // in FK order @Transactional Run each test in a Transaction, rolled back after each test. Use For: Relational DBs In Large Apps: Check that the state is clean Manual Cleanup Use For: non-transacted resources (eg files, nosql)
  • 13. 112 © VictorRentea.ro a training by If every test class is @Transactional Can I still have problems? YES Intermediate COMMITs aka nested transaction @Transactional(REQUIRES_NEW)
  • 14. 113 © VictorRentea.ro a training by Inserting Test Data repo.save() in @Test in @BeforeEach in superclass in @RegisterExtension (JUnit5) Insert via @Profile A Spring bean persisting data at app startup src/test/resources/data.sql (auto-inserted after src/test/resources/schema.sql creation) @Sql CascadeType.PERSIST helps A LOT !
  • 15. 114 © VictorRentea.ro a training by Running SQL Scripts @Sql @Sql("data.sql") @Sql({"schema.sql", "data.sql"}) On method or class @SqlMergeMode TestClass.testMethod.sql before or after @Test in the same transaction
  • 16. 115 © VictorRentea.ro a training by What DB to use in Tests in-memory H2 (create schema via Hibernate) Same DB in Local Docker (create schema via scripts) Personal Schema on Physical DB (eg. REGLISS_VICTOR) Shared Test Schema on Physical DB Legacy 500+ tables schemas For PL/SQL, native features For JPA + native standard SQL
  • 17. 116 © VictorRentea.ro a training by Invest hours, days, weeks to Make Your Test run on CI
  • 18. 117 © VictorRentea.ro a training by Assertions.* assertThat(scoreStr).isEqualTo("Game won"); assertThat(list).anyMatch(e -> e.getX() == 1); .doesNotContain(2); .containsExactlyInAnyOrder(1,2,3); .isEmpty(); assertThatThrownBy(() -> prod()) .hasMessageContaining("address"); +50 more <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> </dependency> +60 more Actual>Expected Expected empty but was: <list.toString()> Expressive Failure Message: Testing Collections Exceptions: assertThat(list.stream().map(...))
  • 19. 118 © VictorRentea.ro a training by @txn Feature: Records Search Background: Given Supplier "X" exists Scenario Outline: Product Search Given One product exists And That product has name "<productName>" When The search criteria name is "<searchName>" Then That product is returned by search: "<returned>" Examples: | productName | searchName | returned | | a | X | false | | a | a | true | Gherkin Language wasted effort if business never sees it * ≈ @Before = Separate transaction / test .feature
  • 21. 120 © VictorRentea.ro a training by @Bean @Mock
  • 22. 121 © VictorRentea.ro a training by @Bean @Mock Replaces that bean with a Mockito Mock Auto-reset() after each @Test
  • 23. 123 © VictorRentea.ro a training by Application Context is Reused Starting Spring is slow. Pro Tip: Maximize Reuse by test classes with the same: @ActiveProfiles @MockBean set custom properties locations= .xml config classes= .class more
  • 24. 124 © VictorRentea.ro a training by Faster Spring Tests 1. Tune JVM: -ea -noverify -mx2048m -XX:TieredStopAtLevel=1 Debugging Test Context reuse: logging.level.org.springframework.test.context.cache=DEBUG 4. Reuse Contexts: reduce no of Spring Banners on Jenkins 6. Disable/Limit Auto-Configuration 2. Lazy-Load only Tested Beans: spring.main.lazy-initialization=true 3. Disable Web: @SpringBootTest(webEnvironment = NONE) https://stackoverflow.com/a/49663075 = +30 sec test run time 5. Run in parallel
  • 25. 125 © VictorRentea.ro a training by Reusing Test Context @SpringBootTest @Transactional @ActiveProfiles({"db-mem", "test"}) public abstract class SpringTestBase { @MockBean protected FileRepo fileRepoMock; ... all @MockBeans ever needed } @ActiveProfiles("db-mem") public class FeedProcessorWithMockTest extends SpringTestBase { @MockBean when(fileRepoMock).then... } nothing requiring dedicated context
  • 26. 126 © VictorRentea.ro a training by WireMock
  • 27. 127 © VictorRentea.ro a training by WireMock.stubFor(get(urlEqualTo("/some/thing")) .withHeader("Accept", equalTo("text/xml")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{"id":12, "value":"WireMock"}]"))); B) Programmatically { "request": { "method": "GET", "url": "/some/thing" }, "response": { "status": 200, "body": "Hello WireMock!", "headers": { "Content-Type": "text/plain" } } } A) via .json config files: Templatize content from a .json file on disk Record them from real systems http://wiremock.org/docs/running-standalone/ WireMock
  • 28. 138 © VictorRentea.ro a training by My Application SafetyClient @MockBean In-memory DB (H2) ProductRepo Remote Sever Real DB @Transactional WireMock Local Docker Real DB .feature What We've Covered @DirtiesContext ProductService @Transactional
  • 29. 139 © VictorRentea.ro a training by files databases queues web services Integration Tests
  • 30. 140 © VictorRentea.ro a training by Unit Tests Integration Deep many layers Fast eg. 100 tests/sec Slow app startup, network ... or Slow in-mem DB, Spring, Docker Tiny fine-grained extensive mocks Fragile DB, REST APIs, files
  • 31. Company Training: victorrentea@gmail.com Training for You: victorrentea.teachable.com Thank You! @victorrentea Blog, Talks, Curricula: victorrentea.ro