SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler offline
1 © VictorRentea.ro
a training by
Tes$ng Microservices
Join the Revolu-on !
at
victorrentea@gmail.com VictorRentea.ro @victorrentea
victorrentea.ro/training-offer
👋 Hi, I'm Victor Rentea 🇷🇴 PhD(CS): VictorRentea.ro
Java Champion, 18 years of code, 10 years of teaching
Consultant & Trainer for 120+ companies:
❤ Clean Code, Architecture, Unit Tes3ng
🛠 Spring, Hibernate, Reac3ve/WebFlux
⚡ Java Performance, Secure Coding 🔐
Lots of EducaHve Conference Talks on YouTube
Founder of European So<ware Cra<ers Community (6K members)
🔥 Free 1-hour webinars, a;er work 👉 victorrentea.ro/community
Past events on youtube.com/vrentea
Father of 👧👦, servant of a 🐈, weekend gardener 🌼 VictorRentea.ro
4 © VictorRentea.ro
a training by
https://martinfowler.com/articles/practical-test-pyramid.html
E2E
Tes$ng Pyramid
Test a thin slice of behavior
Test a group of modules
Test everything as whole
⭐ Deep Edge Case
⭐ Cri4cal Business Flow (eg. checkout)
overlapping is expected
surface is propor9onal to quan9ty
5 https://martinfowler.com/articles/practical-test-pyramid.html
End-to-end
The Tes&ng Pyramid
For Monoliths
6
§The Legacy Monolith
can hide huge complexity behind a few entry points
è Tes8ng deep corners only possible with Unit Tests
§Microservices
have more APIs = stable test surfaces
hide less code complexity, but more configura8on risk
è Write more Integra-on Tests è
For Monoliths
7
Integra-on
(one microservice)
Integrated
(en-re ecosystem)
Deploy all microservices in dockers / staging env
Expensive, slow, fragile tests
Use for cri8cal business flows (eg checkout)
Cover one microservice fully
Use for every flow ⭐⭐⭐
Isolate tests without mocks
Cover 1 class/role (Solitary/Social Unit Testsè)
Use for naturally isolated pieces with high complexity.
@Mock are allowed
Honeycomb Tes,ng Strategy
Testcontainers 🐳
WireMock
&co
Contract
Tests
(Pact, SCC)
DB ES Kafka ...
API
many tests on
one entry point
h$ps://engineering.atspo2fy.com/2018/01/tes2ng-of-microservices/
Implementa>on
Detail
(a role)
complexity
decouple and
test in isola4on
8 © VictorRentea.ro
a training by
Unit Tests verify narrow a slice of behavior,
decoupled from dependencies (using Mocks),
without star8ng up the applica8on.
What bugs can slip past Unit Tests?
(lock, tap, doors, umbrella)
- Actual behavior of A does not match the mock(A)
- Bad @Query seman8c
- Framework magic fails to work:
@Transac8onal, @Cacheable, @Secured, @EventListener
- Misconfigured Library: Rabbit, Resilience4j, ...
- The response from an API call is not what you expected
....
9 © VictorRentea.ro
a training by
Integra,on Tests
give us more confidence that our code will really work in Produc8on,
by also covering:
ü The real stuff, without mocks
ü Correct library configura8on
ü Magic features of frameworks
ü Closer aligned to func8onal requirements
10 © VictorRentea.ro
a training by
Integra,on Tes,ng Challenges
🔗 Test Coupling
💥 Flaky Tests
🐢 Slow Tests
🧠 Cogni:ve Load
💰 Investment in CI, libs, training
11 © VictorRentea.ro
a training by
Add a Bit of Code
12 © VictorRentea.ro
a training by
🔗 Test Coupling
13 © VictorRentea.ro
a training by
You run your test suite
Test #13 is RED
To debug it, you run that test alone:
... and test #13 turns GREEN: 😱
??!!!?!
Test Coupling
14 © VictorRentea.ro
a training by
You run your test suite
All GREEN
You add your test
Another later test turns RED❌
(untouched!)
??!!!?!
??!!!?!
Test Coupling #2
15 © VictorRentea.ro
a training by
Test Coupling
Accidental: data forgo>en in ...
§DB
§Queues è drain
§Cache è clear
§State of singletons è reset
IntenConal: Stateful user journey
§Chained calls to mulCple endpoints
16 © VictorRentea.ro
a training by
Cleanup DB
§Manual Delete
- @BeforeEach & @AfterEach void cleanup() {repo.deleteAll();}
§SQL Script
- @Sql(script="classpath:cleanup.sql", phase=BEFORE_TEST_METHOD)
§@Transac4onal on Test Class
- Start each @Test in its own transacCon that is rolled back at the end
- Simplest, but: fails if tested code runs in a different transacCon, and can miss bugs*
§Reboot Spring to recreate in-memory DB/MQ/Mongo...
- @DirtiesContext
§Custom Extension
- eg Truncate all tables you find in DB- link
* h3ps://dev.to/henrykeys/don-t-use-transac>onal-in-tests-40eb
17 © VictorRentea.ro
a training by
ads 10..60 seconds to test -me è
Spring
Longer Build!
DO NOT PUT IT ON CI
Find other ways!
@DirtiesContext
19 © VictorRentea.ro
a training by
If every test leaves the DB empty
you can expect to find nothing in DB
What if we won't expect this?
🤔
20 © VictorRentea.ro
a training by
Test Data Slices
§Uniquely idenCfy our test data
- Don't assume we start on an empty DB
§Examples:
- repo.save(new Supplier()).getId(): supplierId; use it to create a Product
- API: Create Product: productId; Place Order { productId }
- r=uuid(); insert user {name=r}; select * from user where name=r and ...
- Such tests could run in parallel 😬
21 © VictorRentea.ro
a training by
§Dedicated Physical DB (like 00s)
§In-memory DB
- eg: H2 emula8ng SQL syntax via Compa8bility MODE=Oracle (eg)
✅ Simple setup
§Prod-like DB in a Docker 🐳
- eg: postgres:11-my-corp-tweaks spined of by tests via Testcontainers.org
✅ Can run incremental scripts (liquibase, flyway, ...)
✅ Can use DB-specific SQL: CONNECT BY, CONVERT(name, 'US7ASCII'), PL/SQL
What DB to use in Tests?
22 © VictorRentea.ro
a training by
💥 Flaky Tests
23 © VictorRentea.ro
a training by
- The build is failed. It's that test again!
- IDN, It worked on my machine™! Run it again!
(20 minutes later)
- What?! It passed this Cme!
- Told ya!😏
What to do about it?
> Make it reliable, then put it back on CI
⚠ "Tests o)en fail" aVtude is unhealthy
24 © VictorRentea.ro
a training by
CI Retaliates
haps://www.youtube.com/watch?v=1EGk2rvZe8A
25 © VictorRentea.ro
a training by
§Calls systems out of your control 😱
§TesCng work happening in another thread:
- MQ Listeners
- Mul8-threaded: @Async, CompletableFuture.runAsync()
§ Hack: inject a synchronous executor: link
- @Scheduled(rate=/cron=)
§ Consider: disable scheduler + call the method
Flaky? Possible Causes:
26 © VictorRentea.ro
a training by
§Block test:
- Mockito.verify(mock, timeout(1000)).call();
- Blocking message receive
§Callback-based à block the test thread using
- Latch
- CompletableFuture.complete(result)
§Poll for the effect: (how are your clients gonna do it?)
- Awaitility.await().atMost(5, SECONDS)
.pollInterval(50, MILLISECONDS)
.untilAsserted(() -> loanRepo.find(id).status == APPROVED);
Tes$ng Async Work
27 © VictorRentea.ro
a training by
🐢 Slow Tests
28 © VictorRentea.ro
a training by
Build Failed!
😖
29 © VictorRentea.ro
a training by
Build Failed!
30 © VictorRentea.ro
a training by
👍
All tests should complete
in <10..12 minutes
Build Failed!
31 © VictorRentea.ro
a training by
Each banner during tests means += 10..50s build Cme
Spring can Start Slow
32 © VictorRentea.ro
a training by
Spring can Start Slow
The same Spring context is reused
by different test classes
33 © VictorRentea.ro
a training by
§Spring Context is reused across test classes sharing the same:
- @MockBeans
- @Ac+veProfiles
- Proper+es: @TestPropertySource,..
- and others...
§Debug:
- logging.level.org.springframework.test.context.cache=DEBUG (SO answer) and see in log:
- Spring test ApplicaConContext cache staCsCcs: [size = 7, hitCount = 1780, missCount = 7, ...]
§Mul9ple app instances are started at the same 9me⚠
- ⚠ Risk = @Scheduled, Compe8ng message listeners
Spring Context Cache
Reduce number of
unique combina8ons
34 © VictorRentea.ro
a training by
Speeding up Spring Boot Tests
1. Faster VM startup: -ea -noverify -XX:TieredStopAtLevel=1 and grant more memory -mx4G
3. Slice Tests – Don't start unused parts of Spring, eg @DataJpaTest, @WebMvcTest...
h3ps://spring.io/blog/2016/08/30/custom-test-slice-with-spring-boot-1-4 and h3ps://stackoverflow.com/a/49663075
5. Run Tests on Mul>ple Threads - DANGEROUS😱
2. Reuse expensive resources across Test Classes
Ø Spring Context (previous slide)
Ø Testcontainers Dockers 🐳 (SO)
Ø WireMock/MockServer instances
Ø Profile execu>on of your tests è
4. Run fast tests at commit, defer slow tests: @Tag("slow") or ...IT suffix
Run load tests, UI robots, batches, ... only 1-2/day, eg using Maven surefire plugin (at every push) vs failsafe (nightly)
36 © VictorRentea.ro
a training by
Running Tests on Mul$ple Threads
37 © VictorRentea.ro
a training by
Running Tests on Mul$ple Threads
§Can see impressive decrease in Cme (up to - 70%)
☢ Risk: tests race on
- Files, sta8c variables
- @MockBean when/verify 😱
- DB/MQ è use @Transac8onal or test-data-slices
è Run unsafe test class with @Execu8on(SAME_THREAD)
h3ps://www.baeldung.com/junit-5-parallel-tests
38 © VictorRentea.ro
a training by
🧠 Cogni4ve Load
39 © VictorRentea.ro
a training by
Deep Tests
40 © VictorRentea.ro
a training by
Deep Tests Require Tools
§Private helper func:ons to simplify your @Tests
§Object Mother
- Tweak 'standard' test values for your need
§Tes:ng DSL (framework)
- Example: h@ps://github.com/sandromancuso/cleancoders_openchat/blob/openchat-unclebob/src/test-
integra9on/java/integra9on/IT_WallAPI.java
- ⚠ Risk of bugs, hard to evolve
41 © VictorRentea.ro
a training by
Tes$ng DSL
When to build one?
42 © VictorRentea.ro
a training by
Test Classifica$on
for taking decisions
§Reliability
- Reproducible: a failure always means a bug
- Flaky eg. tesCng async code, sleep(2) in tests, Selenium
§Speed
- Fast, in process: eg >100 tests/sec è run on CI at each commit
- Slow: load test, batch ... è run Nightly?
§Scope
- Unit Test of a thin feature slice (white-box)
§ Solitary ~ for a single class
§ Social ~ for a cluster of classes fulfilling a well defined responsibility ❤
- Integra;on Test of a long flow, requiring wider awareness
§ Gray-box: Can access my private DB
§ Black-box: Only uses API calls
- Journey Test – a sequence of steps in a stateful interacCon: eg create>search>get>delete
43 © VictorRentea.ro
a training by
Contract Mismatch
1) Prevent breaking my contract by accident
- Trick: OpenApiFreezeTest.java
2) Did they change their contract?
= Contract TesAng can automa@cally fail a build if it happens
1) Spring Cloud Contract
2) Pact.io (google "pact victorrentea" for more on that J)
44 © VictorRentea.ro
a training by
Start off by writing API-level tests.
Fall back to Unit Tests
when facing too much complexity.
45 © VictorRentea.ro
a training by
Convert Unit to Integration Tests
to cover for more risks.
Do it in baby steps,
measuring the added complexity
(intrinsic and extrinsic).
46 © VictorRentea.ro
a training by
Cover More Risks
ØLonger flows: confidence and robustness
Ø+DB: queries, JPA magic, TransacCons
Ø+WireMock: correct API integraCon
Ø+Queues: config, ack, retries
ØMagic: @Cacheable, @Retry...
ØEnter via REST: ValidaCon, authz, HTTP status ...
ØStart your app in a Docker: config, 99% real, load
47 © VictorRentea.ro
a training by
Take-aways 🍔
🔗 Test IsolaAon: clean up aCer or test-data slices
💥 Flaky Tests: block or poll; test async part separately
🐢 Slow Tests: reuse expensive resources
🧠 CogniAve Load: build a tes@ng DSL (framework)
48 © VictorRentea.ro
a training by
Thank you!
victorrentea@gmail.com VictorRentea.ro @victorrentea

Mais conteúdo relacionado

Mais procurados

Spring cloud for microservices architecture
Spring cloud for microservices architectureSpring cloud for microservices architecture
Spring cloud for microservices architectureIgor Khotin
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
 
Using Azure DevOps to continuously build, test, and deploy containerized appl...
Using Azure DevOps to continuously build, test, and deploy containerized appl...Using Azure DevOps to continuously build, test, and deploy containerized appl...
Using Azure DevOps to continuously build, test, and deploy containerized appl...Adrian Todorov
 
A Roadmap to Cloud Center of Excellence Adoption
A Roadmap to Cloud Center of Excellence AdoptionA Roadmap to Cloud Center of Excellence Adoption
A Roadmap to Cloud Center of Excellence AdoptionAmazon Web Services
 
Continues Integration and Continuous Delivery with Azure DevOps - Deploy Anyt...
Continues Integration and Continuous Delivery with Azure DevOps - Deploy Anyt...Continues Integration and Continuous Delivery with Azure DevOps - Deploy Anyt...
Continues Integration and Continuous Delivery with Azure DevOps - Deploy Anyt...Janusz Nowak
 
Oracle Cloud Infrastructure (OCI)
Oracle Cloud Infrastructure (OCI)Oracle Cloud Infrastructure (OCI)
Oracle Cloud Infrastructure (OCI)emmajones88
 
소프트웨어 아키텍처
소프트웨어 아키텍처소프트웨어 아키텍처
소프트웨어 아키텍처영기 김
 
Google Cloud Platform (GCP).ppt
Google Cloud Platform (GCP).pptGoogle Cloud Platform (GCP).ppt
Google Cloud Platform (GCP).pptPrasad Deshmukh
 
Introduction to the Microsoft Azure Cloud.pptx
Introduction to the Microsoft Azure Cloud.pptxIntroduction to the Microsoft Azure Cloud.pptx
Introduction to the Microsoft Azure Cloud.pptxEverestMedinilla2
 
Kubernetes and Prometheus
Kubernetes and PrometheusKubernetes and Prometheus
Kubernetes and PrometheusWeaveworks
 
Azure Machine Learning
Azure Machine LearningAzure Machine Learning
Azure Machine LearningMostafa
 
Building Slack's internal developer platform as a product.pdf
Building Slack's internal developer platform as a product.pdfBuilding Slack's internal developer platform as a product.pdf
Building Slack's internal developer platform as a product.pdfJavier Turégano Molina
 
Microsoft Azure Active Directory
Microsoft Azure Active DirectoryMicrosoft Azure Active Directory
Microsoft Azure Active DirectoryDavid J Rosenthal
 
Cloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaSCloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaSEDB
 
Microservices, Containers, Docker and a Cloud-Native Architecture in the Midd...
Microservices, Containers, Docker and a Cloud-Native Architecture in the Midd...Microservices, Containers, Docker and a Cloud-Native Architecture in the Midd...
Microservices, Containers, Docker and a Cloud-Native Architecture in the Midd...Kai Wähner
 

Mais procurados (20)

Spring cloud for microservices architecture
Spring cloud for microservices architectureSpring cloud for microservices architecture
Spring cloud for microservices architecture
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
 
Using Azure DevOps to continuously build, test, and deploy containerized appl...
Using Azure DevOps to continuously build, test, and deploy containerized appl...Using Azure DevOps to continuously build, test, and deploy containerized appl...
Using Azure DevOps to continuously build, test, and deploy containerized appl...
 
Azure automation
Azure automationAzure automation
Azure automation
 
A Roadmap to Cloud Center of Excellence Adoption
A Roadmap to Cloud Center of Excellence AdoptionA Roadmap to Cloud Center of Excellence Adoption
A Roadmap to Cloud Center of Excellence Adoption
 
Continues Integration and Continuous Delivery with Azure DevOps - Deploy Anyt...
Continues Integration and Continuous Delivery with Azure DevOps - Deploy Anyt...Continues Integration and Continuous Delivery with Azure DevOps - Deploy Anyt...
Continues Integration and Continuous Delivery with Azure DevOps - Deploy Anyt...
 
Oracle Cloud Infrastructure (OCI)
Oracle Cloud Infrastructure (OCI)Oracle Cloud Infrastructure (OCI)
Oracle Cloud Infrastructure (OCI)
 
소프트웨어 아키텍처
소프트웨어 아키텍처소프트웨어 아키텍처
소프트웨어 아키텍처
 
Google Cloud Platform (GCP).ppt
Google Cloud Platform (GCP).pptGoogle Cloud Platform (GCP).ppt
Google Cloud Platform (GCP).ppt
 
Introduction to the Microsoft Azure Cloud.pptx
Introduction to the Microsoft Azure Cloud.pptxIntroduction to the Microsoft Azure Cloud.pptx
Introduction to the Microsoft Azure Cloud.pptx
 
Kubernetes and Prometheus
Kubernetes and PrometheusKubernetes and Prometheus
Kubernetes and Prometheus
 
Azure Machine Learning
Azure Machine LearningAzure Machine Learning
Azure Machine Learning
 
Building Slack's internal developer platform as a product.pdf
Building Slack's internal developer platform as a product.pdfBuilding Slack's internal developer platform as a product.pdf
Building Slack's internal developer platform as a product.pdf
 
MULTI-CLOUD ARCHITECTURE
MULTI-CLOUD ARCHITECTUREMULTI-CLOUD ARCHITECTURE
MULTI-CLOUD ARCHITECTURE
 
Microsoft Azure Active Directory
Microsoft Azure Active DirectoryMicrosoft Azure Active Directory
Microsoft Azure Active Directory
 
Oracle Cloud
Oracle CloudOracle Cloud
Oracle Cloud
 
Cloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaSCloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaS
 
Terraform on Azure
Terraform on AzureTerraform on Azure
Terraform on Azure
 
Oracle Cloud Infrastructure
Oracle Cloud InfrastructureOracle Cloud Infrastructure
Oracle Cloud Infrastructure
 
Microservices, Containers, Docker and a Cloud-Native Architecture in the Midd...
Microservices, Containers, Docker and a Cloud-Native Architecture in the Midd...Microservices, Containers, Docker and a Cloud-Native Architecture in the Midd...
Microservices, Containers, Docker and a Cloud-Native Architecture in the Midd...
 

Semelhante a Testing Microservices @DevoxxBE 23.pdf

Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow oneVictor Rentea
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
 
Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzVictor 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
 
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
 
Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"Fwdays
 
What to Do—Develop Your Own Automation or Use Crowdsourced Testing?
What to Do—Develop Your Own Automation or Use Crowdsourced Testing?What to Do—Develop Your Own Automation or Use Crowdsourced Testing?
What to Do—Develop Your Own Automation or Use Crowdsourced Testing?TechWell
 
DevSecCon SG 2018 Fabian Presentation Slides
DevSecCon SG 2018 Fabian Presentation SlidesDevSecCon SG 2018 Fabian Presentation Slides
DevSecCon SG 2018 Fabian Presentation SlidesFab L
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinSigma Software
 
DevSecCon Singapore 2018 - Remove developers’ shameful secrets or simply rem...
DevSecCon Singapore 2018 -  Remove developers’ shameful secrets or simply rem...DevSecCon Singapore 2018 -  Remove developers’ shameful secrets or simply rem...
DevSecCon Singapore 2018 - Remove developers’ shameful secrets or simply rem...DevSecCon
 
Jenkins Online Meetup - Automated SLI based Build Validation with Keptn
Jenkins Online Meetup - Automated SLI based Build Validation with KeptnJenkins Online Meetup - Automated SLI based Build Validation with Keptn
Jenkins Online Meetup - Automated SLI based Build Validation with KeptnAndreas Grabner
 
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
 
Test driven development_continuous_integration
Test driven development_continuous_integrationTest driven development_continuous_integration
Test driven development_continuous_integrationhaochenglee
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hintsVictor 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
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafMasatoshi Tada
 
Hands On with Selenium and WebDriver
Hands On with Selenium and WebDriverHands On with Selenium and WebDriver
Hands On with Selenium and WebDriverTechWell
 
Codeception introduction and use in Yii
Codeception introduction and use in YiiCodeception introduction and use in Yii
Codeception introduction and use in YiiIlPeach
 

Semelhante a Testing Microservices @DevoxxBE 23.pdf (20)

Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow one
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX Mainz
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
 
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
 
Azure from scratch part 4
Azure from scratch part 4Azure from scratch part 4
Azure from scratch part 4
 
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
 
Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"
 
What to Do—Develop Your Own Automation or Use Crowdsourced Testing?
What to Do—Develop Your Own Automation or Use Crowdsourced Testing?What to Do—Develop Your Own Automation or Use Crowdsourced Testing?
What to Do—Develop Your Own Automation or Use Crowdsourced Testing?
 
DevSecCon SG 2018 Fabian Presentation Slides
DevSecCon SG 2018 Fabian Presentation SlidesDevSecCon SG 2018 Fabian Presentation Slides
DevSecCon SG 2018 Fabian Presentation Slides
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita Galkin
 
DevSecCon Singapore 2018 - Remove developers’ shameful secrets or simply rem...
DevSecCon Singapore 2018 -  Remove developers’ shameful secrets or simply rem...DevSecCon Singapore 2018 -  Remove developers’ shameful secrets or simply rem...
DevSecCon Singapore 2018 - Remove developers’ shameful secrets or simply rem...
 
Jenkins Online Meetup - Automated SLI based Build Validation with Keptn
Jenkins Online Meetup - Automated SLI based Build Validation with KeptnJenkins Online Meetup - Automated SLI based Build Validation with Keptn
Jenkins Online Meetup - Automated SLI based Build Validation with Keptn
 
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
 
Test driven development_continuous_integration
Test driven development_continuous_integrationTest driven development_continuous_integration
Test driven development_continuous_integration
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
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
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with Thymeleaf
 
Hands On with Selenium and WebDriver
Hands On with Selenium and WebDriverHands On with Selenium and WebDriver
Hands On with Selenium and WebDriver
 
Codeception introduction and use in Yii
Codeception introduction and use in YiiCodeception introduction and use in Yii
Codeception introduction and use in Yii
 

Mais de Victor 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
 
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
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixVictor 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
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicVictor 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
 
Don't Be Mocked by your Mocks - Best Practices using Mocks
Don't Be Mocked by your Mocks - Best Practices using MocksDon't Be Mocked by your Mocks - Best Practices using Mocks
Don't Be Mocked by your Mocks - Best Practices using MocksVictor 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
 

Mais de Victor Rentea (20)

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
 
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
 
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
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
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
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
 
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 ...
 
Don't Be Mocked by your Mocks - Best Practices using Mocks
Don't Be Mocked by your Mocks - Best Practices using MocksDon't Be Mocked by your Mocks - Best Practices using Mocks
Don't Be Mocked by your Mocks - Best Practices using Mocks
 
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...
 

Último

Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfQ-Advise
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfsteffenkarlsson2
 
Sourcing Success - How to Find a Clothing Manufacturer
Sourcing Success - How to Find a Clothing ManufacturerSourcing Success - How to Find a Clothing Manufacturer
Sourcing Success - How to Find a Clothing ManufacturerWave PLM
 
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024MulesoftMunichMeetup
 
A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfICS
 
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024SimonedeGijt
 
Malaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptxMalaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptxMok TH
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignNeo4j
 
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...OnePlan Solutions
 
Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024Chirag Panchal
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabbereGrabber
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletAndrea Goulet
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationHelp Desk Migration
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesNeo4j
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfSrushith Repakula
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMarkus Moeller
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024vaibhav130304
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdftimtebeek1
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfkalichargn70th171
 

Último (20)

Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
Sourcing Success - How to Find a Clothing Manufacturer
Sourcing Success - How to Find a Clothing ManufacturerSourcing Success - How to Find a Clothing Manufacturer
Sourcing Success - How to Find a Clothing Manufacturer
 
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
 
A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdf
 
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
 
Malaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptxMalaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptx
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by Design
 
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
 
Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data Migration
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
 

Testing Microservices @DevoxxBE 23.pdf

  • 1. 1 © VictorRentea.ro a training by Tes$ng Microservices Join the Revolu-on ! at victorrentea@gmail.com VictorRentea.ro @victorrentea
  • 2. victorrentea.ro/training-offer 👋 Hi, I'm Victor Rentea 🇷🇴 PhD(CS): VictorRentea.ro Java Champion, 18 years of code, 10 years of teaching Consultant & Trainer for 120+ companies: ❤ Clean Code, Architecture, Unit Tes3ng 🛠 Spring, Hibernate, Reac3ve/WebFlux ⚡ Java Performance, Secure Coding 🔐 Lots of EducaHve Conference Talks on YouTube Founder of European So<ware Cra<ers Community (6K members) 🔥 Free 1-hour webinars, a;er work 👉 victorrentea.ro/community Past events on youtube.com/vrentea Father of 👧👦, servant of a 🐈, weekend gardener 🌼 VictorRentea.ro
  • 3. 4 © VictorRentea.ro a training by https://martinfowler.com/articles/practical-test-pyramid.html E2E Tes$ng Pyramid Test a thin slice of behavior Test a group of modules Test everything as whole ⭐ Deep Edge Case ⭐ Cri4cal Business Flow (eg. checkout) overlapping is expected surface is propor9onal to quan9ty
  • 5. 6 §The Legacy Monolith can hide huge complexity behind a few entry points è Tes8ng deep corners only possible with Unit Tests §Microservices have more APIs = stable test surfaces hide less code complexity, but more configura8on risk è Write more Integra-on Tests è For Monoliths
  • 6. 7 Integra-on (one microservice) Integrated (en-re ecosystem) Deploy all microservices in dockers / staging env Expensive, slow, fragile tests Use for cri8cal business flows (eg checkout) Cover one microservice fully Use for every flow ⭐⭐⭐ Isolate tests without mocks Cover 1 class/role (Solitary/Social Unit Testsè) Use for naturally isolated pieces with high complexity. @Mock are allowed Honeycomb Tes,ng Strategy Testcontainers 🐳 WireMock &co Contract Tests (Pact, SCC) DB ES Kafka ... API many tests on one entry point h$ps://engineering.atspo2fy.com/2018/01/tes2ng-of-microservices/ Implementa>on Detail (a role) complexity decouple and test in isola4on
  • 7. 8 © VictorRentea.ro a training by Unit Tests verify narrow a slice of behavior, decoupled from dependencies (using Mocks), without star8ng up the applica8on. What bugs can slip past Unit Tests? (lock, tap, doors, umbrella) - Actual behavior of A does not match the mock(A) - Bad @Query seman8c - Framework magic fails to work: @Transac8onal, @Cacheable, @Secured, @EventListener - Misconfigured Library: Rabbit, Resilience4j, ... - The response from an API call is not what you expected ....
  • 8. 9 © VictorRentea.ro a training by Integra,on Tests give us more confidence that our code will really work in Produc8on, by also covering: ü The real stuff, without mocks ü Correct library configura8on ü Magic features of frameworks ü Closer aligned to func8onal requirements
  • 9. 10 © VictorRentea.ro a training by Integra,on Tes,ng Challenges 🔗 Test Coupling 💥 Flaky Tests 🐢 Slow Tests 🧠 Cogni:ve Load 💰 Investment in CI, libs, training
  • 10. 11 © VictorRentea.ro a training by Add a Bit of Code
  • 11. 12 © VictorRentea.ro a training by 🔗 Test Coupling
  • 12. 13 © VictorRentea.ro a training by You run your test suite Test #13 is RED To debug it, you run that test alone: ... and test #13 turns GREEN: 😱 ??!!!?! Test Coupling
  • 13. 14 © VictorRentea.ro a training by You run your test suite All GREEN You add your test Another later test turns RED❌ (untouched!) ??!!!?! ??!!!?! Test Coupling #2
  • 14. 15 © VictorRentea.ro a training by Test Coupling Accidental: data forgo>en in ... §DB §Queues è drain §Cache è clear §State of singletons è reset IntenConal: Stateful user journey §Chained calls to mulCple endpoints
  • 15. 16 © VictorRentea.ro a training by Cleanup DB §Manual Delete - @BeforeEach & @AfterEach void cleanup() {repo.deleteAll();} §SQL Script - @Sql(script="classpath:cleanup.sql", phase=BEFORE_TEST_METHOD) §@Transac4onal on Test Class - Start each @Test in its own transacCon that is rolled back at the end - Simplest, but: fails if tested code runs in a different transacCon, and can miss bugs* §Reboot Spring to recreate in-memory DB/MQ/Mongo... - @DirtiesContext §Custom Extension - eg Truncate all tables you find in DB- link * h3ps://dev.to/henrykeys/don-t-use-transac>onal-in-tests-40eb
  • 16. 17 © VictorRentea.ro a training by ads 10..60 seconds to test -me è Spring Longer Build! DO NOT PUT IT ON CI Find other ways! @DirtiesContext
  • 17. 19 © VictorRentea.ro a training by If every test leaves the DB empty you can expect to find nothing in DB What if we won't expect this? 🤔
  • 18. 20 © VictorRentea.ro a training by Test Data Slices §Uniquely idenCfy our test data - Don't assume we start on an empty DB §Examples: - repo.save(new Supplier()).getId(): supplierId; use it to create a Product - API: Create Product: productId; Place Order { productId } - r=uuid(); insert user {name=r}; select * from user where name=r and ... - Such tests could run in parallel 😬
  • 19. 21 © VictorRentea.ro a training by §Dedicated Physical DB (like 00s) §In-memory DB - eg: H2 emula8ng SQL syntax via Compa8bility MODE=Oracle (eg) ✅ Simple setup §Prod-like DB in a Docker 🐳 - eg: postgres:11-my-corp-tweaks spined of by tests via Testcontainers.org ✅ Can run incremental scripts (liquibase, flyway, ...) ✅ Can use DB-specific SQL: CONNECT BY, CONVERT(name, 'US7ASCII'), PL/SQL What DB to use in Tests?
  • 20. 22 © VictorRentea.ro a training by 💥 Flaky Tests
  • 21. 23 © VictorRentea.ro a training by - The build is failed. It's that test again! - IDN, It worked on my machine™! Run it again! (20 minutes later) - What?! It passed this Cme! - Told ya!😏 What to do about it? > Make it reliable, then put it back on CI ⚠ "Tests o)en fail" aVtude is unhealthy
  • 22. 24 © VictorRentea.ro a training by CI Retaliates haps://www.youtube.com/watch?v=1EGk2rvZe8A
  • 23. 25 © VictorRentea.ro a training by §Calls systems out of your control 😱 §TesCng work happening in another thread: - MQ Listeners - Mul8-threaded: @Async, CompletableFuture.runAsync() § Hack: inject a synchronous executor: link - @Scheduled(rate=/cron=) § Consider: disable scheduler + call the method Flaky? Possible Causes:
  • 24. 26 © VictorRentea.ro a training by §Block test: - Mockito.verify(mock, timeout(1000)).call(); - Blocking message receive §Callback-based à block the test thread using - Latch - CompletableFuture.complete(result) §Poll for the effect: (how are your clients gonna do it?) - Awaitility.await().atMost(5, SECONDS) .pollInterval(50, MILLISECONDS) .untilAsserted(() -> loanRepo.find(id).status == APPROVED); Tes$ng Async Work
  • 25. 27 © VictorRentea.ro a training by 🐢 Slow Tests
  • 26. 28 © VictorRentea.ro a training by Build Failed! 😖
  • 27. 29 © VictorRentea.ro a training by Build Failed!
  • 28. 30 © VictorRentea.ro a training by 👍 All tests should complete in <10..12 minutes Build Failed!
  • 29. 31 © VictorRentea.ro a training by Each banner during tests means += 10..50s build Cme Spring can Start Slow
  • 30. 32 © VictorRentea.ro a training by Spring can Start Slow The same Spring context is reused by different test classes
  • 31. 33 © VictorRentea.ro a training by §Spring Context is reused across test classes sharing the same: - @MockBeans - @Ac+veProfiles - Proper+es: @TestPropertySource,.. - and others... §Debug: - logging.level.org.springframework.test.context.cache=DEBUG (SO answer) and see in log: - Spring test ApplicaConContext cache staCsCcs: [size = 7, hitCount = 1780, missCount = 7, ...] §Mul9ple app instances are started at the same 9me⚠ - ⚠ Risk = @Scheduled, Compe8ng message listeners Spring Context Cache Reduce number of unique combina8ons
  • 32. 34 © VictorRentea.ro a training by Speeding up Spring Boot Tests 1. Faster VM startup: -ea -noverify -XX:TieredStopAtLevel=1 and grant more memory -mx4G 3. Slice Tests – Don't start unused parts of Spring, eg @DataJpaTest, @WebMvcTest... h3ps://spring.io/blog/2016/08/30/custom-test-slice-with-spring-boot-1-4 and h3ps://stackoverflow.com/a/49663075 5. Run Tests on Mul>ple Threads - DANGEROUS😱 2. Reuse expensive resources across Test Classes Ø Spring Context (previous slide) Ø Testcontainers Dockers 🐳 (SO) Ø WireMock/MockServer instances Ø Profile execu>on of your tests è 4. Run fast tests at commit, defer slow tests: @Tag("slow") or ...IT suffix Run load tests, UI robots, batches, ... only 1-2/day, eg using Maven surefire plugin (at every push) vs failsafe (nightly)
  • 33. 36 © VictorRentea.ro a training by Running Tests on Mul$ple Threads
  • 34. 37 © VictorRentea.ro a training by Running Tests on Mul$ple Threads §Can see impressive decrease in Cme (up to - 70%) ☢ Risk: tests race on - Files, sta8c variables - @MockBean when/verify 😱 - DB/MQ è use @Transac8onal or test-data-slices è Run unsafe test class with @Execu8on(SAME_THREAD) h3ps://www.baeldung.com/junit-5-parallel-tests
  • 35. 38 © VictorRentea.ro a training by 🧠 Cogni4ve Load
  • 36. 39 © VictorRentea.ro a training by Deep Tests
  • 37. 40 © VictorRentea.ro a training by Deep Tests Require Tools §Private helper func:ons to simplify your @Tests §Object Mother - Tweak 'standard' test values for your need §Tes:ng DSL (framework) - Example: h@ps://github.com/sandromancuso/cleancoders_openchat/blob/openchat-unclebob/src/test- integra9on/java/integra9on/IT_WallAPI.java - ⚠ Risk of bugs, hard to evolve
  • 38. 41 © VictorRentea.ro a training by Tes$ng DSL When to build one?
  • 39. 42 © VictorRentea.ro a training by Test Classifica$on for taking decisions §Reliability - Reproducible: a failure always means a bug - Flaky eg. tesCng async code, sleep(2) in tests, Selenium §Speed - Fast, in process: eg >100 tests/sec è run on CI at each commit - Slow: load test, batch ... è run Nightly? §Scope - Unit Test of a thin feature slice (white-box) § Solitary ~ for a single class § Social ~ for a cluster of classes fulfilling a well defined responsibility ❤ - Integra;on Test of a long flow, requiring wider awareness § Gray-box: Can access my private DB § Black-box: Only uses API calls - Journey Test – a sequence of steps in a stateful interacCon: eg create>search>get>delete
  • 40. 43 © VictorRentea.ro a training by Contract Mismatch 1) Prevent breaking my contract by accident - Trick: OpenApiFreezeTest.java 2) Did they change their contract? = Contract TesAng can automa@cally fail a build if it happens 1) Spring Cloud Contract 2) Pact.io (google "pact victorrentea" for more on that J)
  • 41. 44 © VictorRentea.ro a training by Start off by writing API-level tests. Fall back to Unit Tests when facing too much complexity.
  • 42. 45 © VictorRentea.ro a training by Convert Unit to Integration Tests to cover for more risks. Do it in baby steps, measuring the added complexity (intrinsic and extrinsic).
  • 43. 46 © VictorRentea.ro a training by Cover More Risks ØLonger flows: confidence and robustness Ø+DB: queries, JPA magic, TransacCons Ø+WireMock: correct API integraCon Ø+Queues: config, ack, retries ØMagic: @Cacheable, @Retry... ØEnter via REST: ValidaCon, authz, HTTP status ... ØStart your app in a Docker: config, 99% real, load
  • 44. 47 © VictorRentea.ro a training by Take-aways 🍔 🔗 Test IsolaAon: clean up aCer or test-data slices 💥 Flaky Tests: block or poll; test async part separately 🐢 Slow Tests: reuse expensive resources 🧠 CogniAve Load: build a tes@ng DSL (framework)
  • 45. 48 © VictorRentea.ro a training by Thank you! victorrentea@gmail.com VictorRentea.ro @victorrentea