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
200
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 - Seattle 2025-11-18
sullis
0
34
Dependency Management for Java - Portland - 2025-11-04
sullis
0
20
Dependency management for Java applications 2025-09-11
sullis
0
29
S3 NYC Iceberg meetup 2025-07-10
sullis
0
52
Amazon S3 Chicago 2025-06-04
sullis
0
120
Amazon S3 Boston 2025-05-07
sullis
0
97
Netty ConFoo Montreal 2025-02-27
sullis
0
130
GitHub Actions ConFoo Montreal 2025-02-26
sullis
0
97
Netty Portland Java User Group 2025-02-18
sullis
0
33
Other Decks in Programming
See All in Programming
Rで始めるML・LLM活用入門
wakamatsu_takumu
0
140
nilとは何か 〜interfaceの構造とnil!=nilから理解する〜
kuro_kurorrr
3
1.6k
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
350
Claude Codeと2つの巻き戻し戦略 / Two Rewind Strategies with Claude Code
fruitriin
0
200
文字コードの話
qnighy
43
16k
クライアントワークでSREをするということ。あるいは事業会社におけるSREと同じこと・違うこと
nnaka2992
1
290
AWS Infrastructure as Code の新機能 2025 総まとめ 〜SA 4人による怒涛のデモ祭り〜
konokenj
10
3.1k
朝日新聞のデジタル版を支えるGoバックエンド ー価値ある情報をいち早く確実にお届けするために
junkiishida
1
330
CSC307 Lecture 11
javiergs
PRO
0
580
LangChain4jとは一味違うLangChain4j-CDI
kazumura
1
130
AI主導でFastAPIのWebサービスを作るときに 人間が構造化すべき境界線
okajun35
0
470
Agent Skills Workshop - AIへの頼み方を仕組み化する
gotalab555
13
7.7k
Featured
See All Featured
Chasing Engaging Ingredients in Design
codingconduct
0
130
The SEO identity crisis: Don't let AI make you average
varn
0
400
The State of eCommerce SEO: How to Win in Today's Products SERPs - #SEOweek
aleyda
2
9.7k
The Organizational Zoo: Understanding Human Behavior Agility Through Metaphoric Constructive Conversations (based on the works of Arthur Shelley, Ph.D)
kimpetersen
PRO
0
260
The Language of Interfaces
destraynor
162
26k
BBQ
matthewcrist
89
10k
State of Search Keynote: SEO is Dead Long Live SEO
ryanjones
0
140
The Cost Of JavaScript in 2023
addyosmani
55
9.7k
For a Future-Friendly Web
brad_frost
183
10k
Bash Introduction
62gerente
615
210k
Fashionably flexible responsive web design (full day workshop)
malarkey
408
66k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
249
1.3M
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