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
Netty Chicago Java User Group 2024-04-17
sullis
0
240
Java 21 - Portland Java User Group 2023-10-24
sullis
0
230
Microbenchmarking with JMH - Portland 2023-03-14
sullis
0
100
Code generation on the Java VM 2022-04-19
sullis
0
83
GitHub Actions 2021-12-16
sullis
0
28
Apache Struts and the Equifax data breach 2021-06-03
sullis
0
46
Guardrail State of the Union 2021-04-13
sullis
0
280
Guardrail: State of the Union 2021-03-18
sullis
0
140
Java on AWS 2020-12-15
sullis
0
200
Other Decks in Programming
See All in Programming
チーム立ち上げにAWSを活用したらClaudeさんに褒められた話
mkdev10
3
230
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
0
100
TypeScriptのパフォーマンス改善
yajihum
12
4.9k
JavaScript Closure
asoluka
0
1.9k
戦略的DDDは重いのか? / Is strategic DDD heavy?
pictiny
3
2k
2024 コーディング研修
ckazu
2
620
Amazon Aurora Serverless v2が意外と高かった話と、AWS Database Migration Serviceの話
satoshi256kbyte
1
100
Komplexe Oberflächen mit SVG und der Web Animation API
joergneumann
0
690
Apache Hive 4 on Treasure Data
ryukobayashi
1
470
CDKコントリビュートの最初の壁を越えよう! -簡単issueの見つけ方-
badmintoncryer
3
410
Webアプリをできるだけコードを手書きしないで作ってみる
tomokusaba
2
230
An adventure of Happy Eyeballs
coe401_
1
130
Featured
See All Featured
5 minutes of I Can Smell Your CMS
philhawksworth
199
19k
Code Review Best Practice
trishagee
56
15k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
242
1.2M
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
501
140k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
660
120k
Designing for humans not robots
tammielis
247
25k
The World Runs on Bad Software
bkeepers
PRO
61
6.7k
Building an army of robots
kneath
300
41k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
21
1.6k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
26
2.3k
Principles of Awesome APIs and How to Build Them.
keavy
121
16k
Become a Pro
speakerdeck
PRO
13
4.6k
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