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
sullis
January 25, 2022
Programming
0
190
Mockito 2022-01-25
Unit testing with Mockito
Portland Java User Group
January 25, 2022
#java
#mockito
sullis
January 25, 2022
Tweet
Share
More Decks by sullis
See All by sullis
Dependency management for Java applications 2025-09-11
sullis
0
13
S3 NYC Iceberg meetup 2025-07-10
sullis
0
43
Amazon S3 Chicago 2025-06-04
sullis
0
110
Amazon S3 Boston 2025-05-07
sullis
0
60
Netty ConFoo Montreal 2025-02-27
sullis
0
110
GitHub Actions ConFoo Montreal 2025-02-26
sullis
0
68
Netty Portland Java User Group 2025-02-18
sullis
0
14
Amazon S3 NYJavaSIG 2024-12-12
sullis
0
190
Amazon S3 - Portland Java User Group 2024-09-17
sullis
0
120
Other Decks in Programming
See All in Programming
Pull-Requestの内容を1クリックで動作確認可能にするワークフロー
natmark
2
500
あなたとKaigi on Rails / Kaigi on Rails + You
shimoju
0
130
2分台で1500examples完走!爆速CIを支える環境構築術 - Kaigi on Rails 2025
falcon8823
3
3.6k
詳しくない分野でのVibe Codingで困ったことと学び/vibe-coding-in-unfamiliar-area
shibayu36
3
4.9k
そのpreloadは必要?見過ごされたpreloadが技術的負債として爆発した日
mugitti9
2
3.3k
ポスターセッション: 「まっすぐ行って、右!」って言ってラズパイカーを動かしたい 〜生成AI × Raspberry Pi Pico × Gradioの試作メモ〜
komofr
0
1.3k
理論と実務のギャップを超える
eycjur
0
130
大規模アプリのDIフレームワーク刷新戦略 ~過去最大規模の並行開発を止めずにアプリ全体に導入するまで~
mot_techtalk
1
440
CSC305 Lecture 05
javiergs
PRO
0
210
Domain-centric? Why Hexagonal, Onion, and Clean Architecture Are Answers to the Wrong Question
olivergierke
2
840
iOSエンジニア向けの英語学習アプリを作る!
yukawashouhei
0
190
開発生産性を上げるための生成AI活用術
starfish719
3
640
Featured
See All Featured
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
12
1.2k
Raft: Consensus for Rubyists
vanstee
139
7.1k
Learning to Love Humans: Emotional Interface Design
aarron
274
41k
Into the Great Unknown - MozCon
thekraken
40
2.1k
Facilitating Awesome Meetings
lara
56
6.6k
Designing for Performance
lara
610
69k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
9
970
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
33
2.5k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
114
20k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
132
19k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
17k
Gamification - CAS2011
davidbonilla
81
5.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