Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Mockito 2022-01-25
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
sullis
January 25, 2022
Programming
210
0
Share
Mockito 2022-01-25
Unit testing with Mockito
Portland Java User Group
January 25, 2022
#java
#mockito
sullis
January 25, 2022
More Decks by sullis
See All by sullis
AI Assisted Software Development - Portland Java User Group - 2026-04-14
sullis
0
31
Dependency Management for Java - Seattle 2025-11-18
sullis
0
43
Dependency Management for Java - Portland - 2025-11-04
sullis
0
26
Dependency management for Java applications 2025-09-11
sullis
0
35
S3 NYC Iceberg meetup 2025-07-10
sullis
0
54
Amazon S3 Chicago 2025-06-04
sullis
0
130
Amazon S3 Boston 2025-05-07
sullis
0
100
Netty ConFoo Montreal 2025-02-27
sullis
0
160
GitHub Actions ConFoo Montreal 2025-02-26
sullis
0
100
Other Decks in Programming
See All in Programming
煩雑なSkills管理をSoC(関心の分離)により解決する――関心を分離し、プロンプトを部品として育てるためのOSSを作った話 / Solving Complex Skills Management Through SoC (Separation of Concerns)
nrslib
4
860
PHPのバージョンアップ時にも役立ったAST(2026年版)
matsuo_atsushi
0
300
LM Linkで(非力な!)ノートPCでローカルLLM
seosoft
0
460
PHPで TLSのプロトコルを実装してみるをもう一度しゃべりたい
higaki_program
0
190
PHP 7.4でもOpenTelemetryゼロコード計装がしたい! / PHPerKaigi 2026
arthur1
1
560
AI時代の脳疲弊と向き合う ~言語学としてのPHP~
sakuraikotone
1
1.9k
アクセシビリティ試験の"その後"を仕組み化する
yuuumiravy
0
110
Running Swift without an OS
kishikawakatsumi
0
760
今年もTECHSCOREブログを書き続けます!
hiraoku101
0
240
PDI: Como Alavancar Sua Carreira e Seu Negócio
marcelgsantos
0
120
ふりがな Deep Dive try! Swift Tokyo 2026
watura
0
190
年間50登壇、単著出版、雑誌寄稿、Podcast出演、YouTube、CM、カンファレンス主催……全部やってみたので面白さ等を比較してみよう / I’ve tried them all, so let’s compare how interesting they are.
nrslib
4
770
Featured
See All Featured
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
0
110
Lightning talk: Run Django tests with GitHub Actions
sabderemane
0
160
Visualization
eitanlees
150
17k
Believing is Seeing
oripsolob
1
110
How to Get Subject Matter Experts Bought In and Actively Contributing to SEO & PR Initiatives.
livdayseo
0
99
Ruling the World: When Life Gets Gamed
codingconduct
0
190
Unlocking the hidden potential of vector embeddings in international SEO
frankvandijk
0
760
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
880
From Legacy to Launchpad: Building Startup-Ready Communities
dugsong
0
190
Code Review Best Practice
trishagee
74
20k
What Being in a Rock Band Can Teach Us About Real World SEO
427marketing
0
210
SEO for Brand Visibility & Recognition
aleyda
0
4.5k
Transcript
Unit testing with Mockito Sean Sullivan Portland Java User Group
January 25, 2022
Unit Tests
• Mockito library • Upgrading to Mockito 4 • Extending
Mockito • Anti-patterns
Mockito is a framework for creating Mock objects
a Mock object mimics the behavior of a real object
Gilt.com checkout system
We wrote unit tests to verify: • happy path •
edge case scenarios • error handling logic
• inventory reservation • payment system • shipping cost calculator
• shipping restrictions • purchase limit service • tax calculator • discount calculator Gilt.com Checkout was dependent upon:
The test suite for Gilt.com Checkout used Mockito
We setup mock objects for: • Payment authorization • Inventory
reservation • Discount redemption • Tax calculation • Shipping calculation
Maven pom.xml <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>4.3.1</version> <scope>test</scope> </dependency>
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.verify; import
static org.mockito.ArgumentMatcher.any;
TaxEngine taxEngine = mock(TaxEngine.class); ShippingCostCalculator shippingCalc = mock(ShippingCostCalculator.class); when(taxEngine.calculate(any())).thenReturn(new Money(5,
USD)); when(shippingCalc.calculate()).thenReturn(shippingInfo);
OrderManager unit test OrderManager manager = new OrderManager( taxEngine, shippingCalc);
manager.sync(order); manager.submit(order); verify(taxEngine, once()).calculate(any()); assertTrue(order.isSubmitted());
Mockito.when
thenReturn
How do I mimic a failure?
use thenThrow
TaxEngine taxEngine = mock(TaxEngine.class); when(taxEngine.calculate(any(), any())) .thenThrow(new TaxViolationException());
Four major versions of Mockito • version 1.x • version
2.x • version 3.x • version 4.x
Upgrading to Mockito 4.x
None
None
None
None
async-http-client PR 1812
async-http-client PR 1812
async-http-client PR 1812
async-http-client PR 1812
async-http-client PR 1812
What if my company has 500 Git repos?
Automated refactoring tool
OpenRewrite https://moderne.io/
OpenRewrite
OpenRewrite
mockito.yml
Extending Mockito
Answer interface public interface Answer<T> { T answerInvocation(InvocationOnMock invocation); }
MockitoPlus library
MockitoPlus
MockitoPlus import static org.mockito.Mockito.mock; import static io.github.mockitoplus.MockitoPlus.when;
MockitoPlus HelloWorld hello = mock(HelloWorld.class); when(hello.sayHello(any())) .thenReturn("bonjour") .failAlternatingInvocations();
MockitoPlus HelloWorld hello = mock(HelloWorld.class); when(hello.sayHello(any())) .thenReturn("bonjour") . fi rstInvocationFails();
MockitoPlus HelloWorld hello = mock(HelloWorld.class); when(hello.sayHello(any())) .thenReturn("bonjour") .intermittentFailures() .randomDelay(Duration.of(500, MILLIS));
Intermittent failures with random delays
Mockito anti-patterns
// anti-pattern List<String> names = mock(List.class); // better List<String> names
= new ArrayList<String>(); anti-pattern
// anti-pattern Optional<String> name = mock(Optional.class); // better Optional<String> name
= Optional.of(“Obama”); anti-pattern
// anti-pattern CompletableFuture<String> f = mock(CompletableFuture.class); // better CompletableFuture<String> f
= CompletableFuture.completedFuture(“bonjour”); anti-pattern
what about Scala?
None
“org.mockito” %% "mockito-scala" % “1.16.34” % Test build.sbt
import org.mockito.scalatest.MockitoSugar Scala trait
Questions?
The End @tinyrobots