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
150
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
Java 21 - Portland Java User Group 2023-10-24
sullis
0
220
Microbenchmarking with JMH - Portland 2023-03-14
sullis
0
95
Code generation on the Java VM 2022-04-19
sullis
0
80
GitHub Actions 2021-12-16
sullis
0
28
Apache Struts and the Equifax data breach 2021-06-03
sullis
0
45
Guardrail State of the Union 2021-04-13
sullis
0
270
Guardrail: State of the Union 2021-03-18
sullis
0
140
Java on AWS 2020-12-15
sullis
0
200
Continuous Delivery with GitHub Actions - DeliveryConf 2020
sullis
0
560
Other Decks in Programming
See All in Programming
Designing for tomorrow's programming workflows
honnibal
PRO
2
110
コーンフレークから始める モデリング会話入門
ogurotakayuki
0
250
1인 개발자로 행복하게 살기 - GDG 송도 헬로월드 2024
benjaminkim
1
5.5k
オブジェクトしこう
okuramasafumi
2
150
object-oriented-conference-2024
fuwasegu
8
2.6k
単体テストを書かない技術 #phpcon_odawara
o0h
PRO
24
7.6k
ドメイン・ファーストで考える問題解決に役立つモデル設計 / Domain First Model Design
suzushin54
2
2k
CircleCIを活用して AWSへの継続的デリバリーを 実践する
coconala_engineer
1
230
フロントエンドパフォーマンス 入門
shouta2
7
1.6k
デザインシステムで Tailwind CSSとCSS in JSに分散投資をしたら良かった話
fsubal
18
4.8k
ADRを一年運用してみた/adr_after_a_year
hanhan1978
7
2.1k
今、知っておきたい! 生成AIエージェントの世界
elith
3
330
Featured
See All Featured
Building a Modern Day E-commerce SEO Strategy
aleyda
16
6.3k
Why Our Code Smells
bkeepers
PRO
330
56k
Build The Right Thing And Hit Your Dates
maggiecrowley
23
2k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
60
14k
Documentation Writing (for coders)
carmenintech
59
3.9k
Statistics for Hackers
jakevdp
789
220k
Scaling GitHub
holman
457
140k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
272
12k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
243
20k
5 minutes of I Can Smell Your CMS
philhawksworth
199
19k
Product Roadmaps are Hard
iamctodd
43
9.7k
Six Lessons from altMBA
skipperchong
19
3k
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