SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the DomainVictor Rentea
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityVictor 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
 
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
 
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
 
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
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
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
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 

Was ist angesagt? (20)

Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
 
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
 
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
 
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
 
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
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Clean Code
Clean CodeClean Code
Clean Code
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
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 and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Clean code
Clean code Clean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Clean code
Clean codeClean code
Clean code
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing ArchitecturesVictor Rentea
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hintsVictor 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
 

Mehr von 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
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
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...
 

Kürzlich hochgeladen

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
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
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Kürzlich hochgeladen (20)

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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 ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 

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