SlideShare a Scribd company logo
1 of 27
Download to read offline
113 © VictorRentea.ro
a training by
Integration Testing
with Spring
victorrentea@gmail.com VictorRentea.ro @victorrentea
All code is at https://github.com/victorrentea/unit-testing.git on branch JAX_Mainz
Victor Rentea
VictorRentea.ro
Blog, Best Talks, Video Courses, ...
Independent Trainer
for companies and individuals
Founder of
Bucharest Software Craftsmanship Community
Java Champion
❤️ Simple Design, Refactoring, Unit Testing ❤️
Technical Training
400 days
(100+ online)
2000 devs
8 years
More details on VictorRentea.ro
50 companies
Reach out
to me:
Hibernate
Spring Functional Prog
Java Performance
Reactive Prog
Design Patterns
Pragmatic DDD
Clean Code
Refactoring
Unit Testing
TDD
any
lang
@victorrentea
Intense
116 © 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 it's them! 🙏
Tests failed
occasionally
some months after...
117 © VictorRentea.ro
a training by
Unit Tests
Integration
failure ➔ maybe a bug
failure ➔ always a bug
119 © VictorRentea.ro
a training by
Zero Tolerance for Failed Tests
120 © VictorRentea.ro
a training by
🚨 USB device connected to Jenkins
121 © 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
122 © VictorRentea.ro
a training by
Testing...
▪with a Database
▪with external REST calls
▪your REST API
Agenda
123 © VictorRentea.ro
a training by
CODE
128 © 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
132 © 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(...);
repo.search(...);
....
}
@DirtiesContext(methodMode = AFTER_METHOD)
Recreates the embedded DB
Use For: debugging (time waste)
repo.deleteAll(); ... // others.deleteAll()… // in FK order
@Transactional Run each test in a Transaction,
rolled back after each test.
Best For: Relational DBs
In Large Apps:
Check that the state is clean
Manual Cleanup
Use For: non-transacted resources (eg files, nosql)
133 © 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)
134 © VictorRentea.ro
a training by
Inserting Test Data
repo.save()
in @Test
@BeforeEach
@BeforeEach in superclass (inheritance)
@RegisterExtension (composition with JUnit5)
Insert via @Profile
A bean persists data at startup
src/test/resources/data.sql
if you use schema.sql
Incremental Scripts
@Sql
135 © VictorRentea.ro
a training by
Composing Fixtures with JUnit5
public class CommonData
implements BeforeEachCallback {
private User user;
public User getUser() {
return user;
}
@Override
public void beforeEach(ExtensionContext context) {
EntityManager em = SpringExtension.getApplicationContext(context)
.getBean(EntityManager.class);
user = new User().setUsername("test");
em.persist(user);
}
}
@RegisterExtension
public CommonData commonData = new CommonData();
@Test
public void noCriteria() {
User user = commonData.getUser();
repo.save(new Post().setCreatedBy(user));
assertThat(repo.findAll()).hasSize(1);
}
in your test class:
136 © VictorRentea.ro
a training by
Running SQL Scripts
@Sql("data.sql")
@Sql(script="classpath:cleanup.sql",
phase=BEFORE_TEST_METHOD)
@interface Cleanup {}
before or after @Test
runs in the same transaction
cleanup or initial data insert
137 © VictorRentea.ro
a training by
What DB to use in Tests
in-memory H2
(create schema via Hibernate)
Same DB with TestContainers
(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, custom DB features
For JPA + native standard SQL
140 © 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
141 © VictorRentea.ro
a training by
142 © VictorRentea.ro
a training by
@Bean
@Mock
Create a Mock
(Mockito)
Define a bean
(Spring)
143 © VictorRentea.ro
a training by
@Bean
@Mock
Replaces that bean with a Mockito Mock
(Auto-reset() after each @Test)
145 © 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
146 © VictorRentea.ro
a training by
= +30 sec test run time
Optimizing Spring Tests Speed
1. Tune JVM: -ea -noverify -mx2048m -XX:TieredStopAtLevel=1
6. Limit Auto-Configuration (aka slice tests)
2. Lazy-Load only Tested Beans: spring.main.lazy-initialization=true
3. Disable Web: @SpringBootTest(webEnvironment = NONE)
https://stackoverflow.com/a/49663075 +
https://spring.io/blog/2016/08/30/custom-test-slice-with-spring-boot-1-4
5. Run in parallel
4. Reuse between Test Classes: Sprint Context (#banners) + Dockers + WireMocks
Debugging Test Context reuse: logging.level.org.springframework.test.context.cache=DEBUG
(Least invasive first)
147 © 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
160 © 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
162 © VictorRentea.ro
a training by
Unit Tests
Integration
Typically Fast
eg. 100 tests/sec
www . A - color . com
... or Slow
Spring, in-mem DB, Docker
failure ➔ maybe a bug
failure ➔ always a bug
Goal
Run all Honest test after commit
Optimize Test Speed
Company Training:
victorrentea@gmail.com
Training for You:
victorrentea.teachable.com
Thank You!
@victorrentea
Blog, Talks, Curricula:
victorrentea.ro

More Related Content

What's hot

Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Victor Rentea
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable ObjectsVictor Rentea
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicVictor Rentea
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixVictor Rentea
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideVictor Rentea
 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Victor Rentea
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......hugo lu
 
Refactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract MethodRefactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract MethodVictor Rentea
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineAnup Singh
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyonddn
 
Pharo Optimising JIT Internals
Pharo Optimising JIT InternalsPharo Optimising JIT Internals
Pharo Optimising JIT InternalsESUG
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Codeerikmsp
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testingsgleadow
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShareyayao
 

What's hot (20)

Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable Objects
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......
 
Refactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract MethodRefactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract Method
 
Test
TestTest
Test
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & Jasmine
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
 
Pharo Optimising JIT Internals
Pharo Optimising JIT InternalsPharo Optimising JIT Internals
Pharo Optimising JIT Internals
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testing
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 

Similar to Integration testing with spring @JAX Mainz

Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfVictor Rentea
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Mark Niebergall
 
Scala, Functional Programming and Team Productivity
Scala, Functional Programming and Team ProductivityScala, Functional Programming and Team Productivity
Scala, Functional Programming and Team Productivity7mind
 
Test Drive Development in Ruby On Rails
Test Drive Development in Ruby On RailsTest Drive Development in Ruby On Rails
Test Drive Development in Ruby On RailsNyros Technologies
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHPRadu Murzea
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hintsVictor Rentea
 
Anatomy of a Build Pipeline
Anatomy of a Build PipelineAnatomy of a Build Pipeline
Anatomy of a Build PipelineSamuel Brown
 
Eclipse MicroProfile: Accelerating the adoption of Java Microservices
Eclipse MicroProfile: Accelerating the adoption of Java MicroservicesEclipse MicroProfile: Accelerating the adoption of Java Microservices
Eclipse MicroProfile: Accelerating the adoption of Java MicroservicesDev_Events
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!Paco van Beckhoven
 
Hands On with Selenium and WebDriver
Hands On with Selenium and WebDriverHands On with Selenium and WebDriver
Hands On with Selenium and WebDriverTechWell
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-appsVenkata Ramana
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django ApplicationsGareth Rushgrove
 
Mutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekMutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekPaco van Beckhoven
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript TestingKissy Team
 
JCD 2013 OCM Java Developer
JCD 2013 OCM Java DeveloperJCD 2013 OCM Java Developer
JCD 2013 OCM Java Developer益裕 張
 
OCM Java 開發人員認證與設計模式
OCM Java 開發人員認證與設計模式OCM Java 開發人員認證與設計模式
OCM Java 開發人員認證與設計模式CodeData
 

Similar to Integration testing with spring @JAX Mainz (20)

Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdf
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
 
Scala, Functional Programming and Team Productivity
Scala, Functional Programming and Team ProductivityScala, Functional Programming and Team Productivity
Scala, Functional Programming and Team Productivity
 
Test Drive Development in Ruby On Rails
Test Drive Development in Ruby On RailsTest Drive Development in Ruby On Rails
Test Drive Development in Ruby On Rails
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHP
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Anatomy of a Build Pipeline
Anatomy of a Build PipelineAnatomy of a Build Pipeline
Anatomy of a Build Pipeline
 
Eclipse MicroProfile: Accelerating the adoption of Java Microservices
Eclipse MicroProfile: Accelerating the adoption of Java MicroservicesEclipse MicroProfile: Accelerating the adoption of Java Microservices
Eclipse MicroProfile: Accelerating the adoption of Java Microservices
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!
 
Hands On with Selenium and WebDriver
Hands On with Selenium and WebDriverHands On with Selenium and WebDriver
Hands On with Selenium and WebDriver
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
Unit testing
Unit testingUnit testing
Unit testing
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
Mutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekMutation testing Bucharest Tech Week
Mutation testing Bucharest Tech Week
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
JCD 2013 OCM Java Developer
JCD 2013 OCM Java DeveloperJCD 2013 OCM Java Developer
JCD 2013 OCM Java Developer
 
OCM Java 開發人員認證與設計模式
OCM Java 開發人員認證與設計模式OCM Java 開發人員認證與設計模式
OCM Java 開發人員認證與設計模式
 

More from Victor Rentea

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Victor Rentea
 
Distributed Consistency.pdf
Distributed Consistency.pdfDistributed Consistency.pdf
Distributed Consistency.pdfVictor Rentea
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteVictor Rentea
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxVictor Rentea
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxVictor Rentea
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java ApplicationVictor Rentea
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxVictor Rentea
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing ArchitecturesVictor Rentea
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfVictor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor Rentea
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the DomainVictor Rentea
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021Victor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor Rentea
 
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Victor Rentea
 

More from Victor Rentea (18)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24
 
Distributed Consistency.pdf
Distributed Consistency.pdfDistributed Consistency.pdf
Distributed Consistency.pdf
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptx
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptx
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021
 
TDD Mantra
TDD MantraTDD Mantra
TDD Mantra
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
 

Recently uploaded

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 

Recently uploaded (20)

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 

Integration testing with spring @JAX Mainz

  • 1. 113 © VictorRentea.ro a training by Integration Testing with Spring victorrentea@gmail.com VictorRentea.ro @victorrentea All code is at https://github.com/victorrentea/unit-testing.git on branch JAX_Mainz
  • 2. Victor Rentea VictorRentea.ro Blog, Best Talks, Video Courses, ... Independent Trainer for companies and individuals Founder of Bucharest Software Craftsmanship Community Java Champion ❤️ Simple Design, Refactoring, Unit Testing ❤️
  • 3. Technical Training 400 days (100+ online) 2000 devs 8 years More details on VictorRentea.ro 50 companies Reach out to me: Hibernate Spring Functional Prog Java Performance Reactive Prog Design Patterns Pragmatic DDD Clean Code Refactoring Unit Testing TDD any lang @victorrentea Intense
  • 4. 116 © 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 it's them! 🙏 Tests failed occasionally some months after...
  • 5. 117 © VictorRentea.ro a training by Unit Tests Integration failure ➔ maybe a bug failure ➔ always a bug
  • 6. 119 © VictorRentea.ro a training by Zero Tolerance for Failed Tests
  • 7. 120 © VictorRentea.ro a training by 🚨 USB device connected to Jenkins
  • 8. 121 © 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. 122 © VictorRentea.ro a training by Testing... ▪with a Database ▪with external REST calls ▪your REST API Agenda
  • 10. 123 © VictorRentea.ro a training by CODE
  • 11. 128 © 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. 132 © 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(...); repo.search(...); .... } @DirtiesContext(methodMode = AFTER_METHOD) Recreates the embedded DB Use For: debugging (time waste) repo.deleteAll(); ... // others.deleteAll()… // in FK order @Transactional Run each test in a Transaction, rolled back after each test. Best For: Relational DBs In Large Apps: Check that the state is clean Manual Cleanup Use For: non-transacted resources (eg files, nosql)
  • 13. 133 © 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. 134 © VictorRentea.ro a training by Inserting Test Data repo.save() in @Test @BeforeEach @BeforeEach in superclass (inheritance) @RegisterExtension (composition with JUnit5) Insert via @Profile A bean persists data at startup src/test/resources/data.sql if you use schema.sql Incremental Scripts @Sql
  • 15. 135 © VictorRentea.ro a training by Composing Fixtures with JUnit5 public class CommonData implements BeforeEachCallback { private User user; public User getUser() { return user; } @Override public void beforeEach(ExtensionContext context) { EntityManager em = SpringExtension.getApplicationContext(context) .getBean(EntityManager.class); user = new User().setUsername("test"); em.persist(user); } } @RegisterExtension public CommonData commonData = new CommonData(); @Test public void noCriteria() { User user = commonData.getUser(); repo.save(new Post().setCreatedBy(user)); assertThat(repo.findAll()).hasSize(1); } in your test class:
  • 16. 136 © VictorRentea.ro a training by Running SQL Scripts @Sql("data.sql") @Sql(script="classpath:cleanup.sql", phase=BEFORE_TEST_METHOD) @interface Cleanup {} before or after @Test runs in the same transaction cleanup or initial data insert
  • 17. 137 © VictorRentea.ro a training by What DB to use in Tests in-memory H2 (create schema via Hibernate) Same DB with TestContainers (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, custom DB features For JPA + native standard SQL
  • 18. 140 © 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
  • 20. 142 © VictorRentea.ro a training by @Bean @Mock Create a Mock (Mockito) Define a bean (Spring)
  • 21. 143 © VictorRentea.ro a training by @Bean @Mock Replaces that bean with a Mockito Mock (Auto-reset() after each @Test)
  • 22. 145 © 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
  • 23. 146 © VictorRentea.ro a training by = +30 sec test run time Optimizing Spring Tests Speed 1. Tune JVM: -ea -noverify -mx2048m -XX:TieredStopAtLevel=1 6. Limit Auto-Configuration (aka slice tests) 2. Lazy-Load only Tested Beans: spring.main.lazy-initialization=true 3. Disable Web: @SpringBootTest(webEnvironment = NONE) https://stackoverflow.com/a/49663075 + https://spring.io/blog/2016/08/30/custom-test-slice-with-spring-boot-1-4 5. Run in parallel 4. Reuse between Test Classes: Sprint Context (#banners) + Dockers + WireMocks Debugging Test Context reuse: logging.level.org.springframework.test.context.cache=DEBUG (Least invasive first)
  • 24. 147 © 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
  • 25. 160 © 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
  • 26. 162 © VictorRentea.ro a training by Unit Tests Integration Typically Fast eg. 100 tests/sec www . A - color . com ... or Slow Spring, in-mem DB, Docker failure ➔ maybe a bug failure ➔ always a bug Goal Run all Honest test after commit Optimize Test Speed
  • 27. Company Training: victorrentea@gmail.com Training for You: victorrentea.teachable.com Thank You! @victorrentea Blog, Talks, Curricula: victorrentea.ro