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
160
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
Amazon S3 - Portland Java User Group 2024-09-17
sullis
0
47
Netty - Montreal Java User Group 2024-05-21
sullis
0
120
Netty Chicago Java User Group 2024-04-17
sullis
0
770
Java 21 - Portland Java User Group 2023-10-24
sullis
0
280
Microbenchmarking with JMH - Portland 2023-03-14
sullis
0
130
Code generation on the Java VM 2022-04-19
sullis
0
110
GitHub Actions 2021-12-16
sullis
0
35
Apache Struts and the Equifax data breach 2021-06-03
sullis
0
54
Guardrail State of the Union 2021-04-13
sullis
0
320
Other Decks in Programming
See All in Programming
2万ページのSSG運用における工夫と注意点 / Vue Fes Japan 2024
chinen
3
1.4k
Macとオーディオ再生 2024/11/02
yusukeito
0
270
ECS Service Connectのこれまでのアップデートと今後のRoadmapを見てみる
tkikuc
2
230
デプロイを任されたので、教わった通りにデプロイしたら障害になった件 ~俺のやらかしを越えてゆけ~
techouse
52
33k
Content Security Policy入門 セキュリティ設定と 違反レポートのはじめ方 / Introduction to Content Security Policy Getting Started with Security Configuration and Violation Reporting
uskey512
1
450
カラム追加で増えるActiveRecordのメモリサイズ イメージできますか?
asayamakk
4
1.7k
Webの技術スタックで マルチプラットフォームアプリ開発を可能にするElixirDesktopの紹介
thehaigo
2
1k
開発効率向上のためのリファクタリングの一歩目の選択肢 ~コード分割~ / JJUG CCC 2024 Fall
ryounasso
0
380
Snowflake x dbtで作るセキュアでアジャイルなデータ基盤
tsoshiro
2
460
C#/.NETのこれまでのふりかえり
tomokusaba
1
170
Dev ContainersとGitHub Codespacesの素敵な関係
ymd65536
1
140
RailsのPull requestsのレビューの時に私が考えていること
yahonda
5
2.3k
Featured
See All Featured
Faster Mobile Websites
deanohume
304
30k
VelocityConf: Rendering Performance Case Studies
addyosmani
325
24k
Git: the NoSQL Database
bkeepers
PRO
426
64k
Why Our Code Smells
bkeepers
PRO
334
57k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
27
800
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
41
2.2k
Learning to Love Humans: Emotional Interface Design
aarron
272
40k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
14
2k
What’s in a name? Adding method to the madness
productmarketing
PRO
22
3.1k
Happy Clients
brianwarren
97
6.7k
How to train your dragon (web standard)
notwaldorf
88
5.7k
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