SlideShare a Scribd company logo
1 of 31
Download to read offline
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

What's hot

Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupVictor 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
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next ChapterVictor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor 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 code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
The Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring FrameworkThe Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring FrameworkVictor Rentea
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing ArchitecturesVictor Rentea
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework OverviewMario Peshev
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses étatsJosé Paumard
 
Py.test
Py.testPy.test
Py.testsoasme
 
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testingKarate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testingRoman Liubun
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoringkim.mens
 

What's hot (20)

Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User Group
 
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
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next Chapter
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
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 coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
The Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring FrameworkThe Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring Framework
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses états
 
Py.test
Py.testPy.test
Py.test
 
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testingKarate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Clean code
Clean codeClean code
Clean code
 

Similar to Integration testing with spring @snow one

Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzVictor Rentea
 
Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfVictor Rentea
 
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
 
Scala, Functional Programming and Team Productivity
Scala, Functional Programming and Team ProductivityScala, Functional Programming and Team Productivity
Scala, Functional Programming and Team Productivity7mind
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on RailsMark Menard
 
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
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript TestingKissy Team
 
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...Cωνσtantίnoς Giannoulis
 
Anatomy of a Build Pipeline
Anatomy of a Build PipelineAnatomy of a Build Pipeline
Anatomy of a Build PipelineSamuel Brown
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App EngineInphina Technologies
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App EngineIndicThreads
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choicetoddbr
 
MicroProfile Devoxx.us
MicroProfile Devoxx.usMicroProfile Devoxx.us
MicroProfile Devoxx.usjclingan
 
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
 
Unit Testing Documentum Foundation Classes Code
Unit Testing Documentum Foundation Classes CodeUnit Testing Documentum Foundation Classes Code
Unit Testing Documentum Foundation Classes CodeBlueFish
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails AppsRabble .
 
Ahesanali Vijapura - QA Manager
Ahesanali Vijapura - QA ManagerAhesanali Vijapura - QA Manager
Ahesanali Vijapura - QA Managerahesanvijapura
 

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

Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX Mainz
 
Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdf
 
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
 
Scala, Functional Programming and Team Productivity
Scala, Functional Programming and Team ProductivityScala, Functional Programming and Team Productivity
Scala, Functional Programming and Team Productivity
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on Rails
 
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
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
 
Anatomy of a Build Pipeline
Anatomy of a Build PipelineAnatomy of a Build Pipeline
Anatomy of a Build Pipeline
 
Ravindra Kumar
Ravindra KumarRavindra Kumar
Ravindra Kumar
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App Engine
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
Automated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choiceAutomated Acceptance Tests & Tool choice
Automated Acceptance Tests & Tool choice
 
Codeception
CodeceptionCodeception
Codeception
 
MicroProfile Devoxx.us
MicroProfile Devoxx.usMicroProfile Devoxx.us
MicroProfile Devoxx.us
 
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
 
Unit Testing Documentum Foundation Classes Code
Unit Testing Documentum Foundation Classes CodeUnit Testing Documentum Foundation Classes Code
Unit Testing Documentum Foundation Classes Code
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Ahesanali Vijapura - QA Manager
Ahesanali Vijapura - QA ManagerAhesanali Vijapura - QA Manager
Ahesanali Vijapura - QA Manager
 

More from Victor 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
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hintsVictor 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
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicVictor Rentea
 
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021Victor Rentea
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Victor Rentea
 
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...Victor Rentea
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable ObjectsVictor Rentea
 
Definitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in JavaDefinitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in JavaVictor 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 (19)

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
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
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
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
 
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021
 
TDD Mantra
TDD MantraTDD Mantra
TDD Mantra
 
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable Objects
 
Definitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in JavaDefinitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in Java
 
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

Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 

Recently uploaded (20)

Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 

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