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
250
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
84
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
哲学史とモデリング
tanakahisateru
3
440
Docker_OSS_ホスティング入門
satokoki645
0
140
『WordPressコミュニティで学ぶ』OSS貢献の多様性
ippey
0
300
slog登場に伴うloggerの取り回し手法の見直し / kamakura.go #6
arthur1
0
170
WebGLで始める コンピュータグラフィックス入門
heller77
0
390
Documentation testsの恩恵 / Documentation testing benefits
ssssota
1
570
[RailsConf Detroit 2024] Ruby on Fails - effective error handling with Rails conventions
talyssonoc
0
300
“Seeing Like a Programmer”—Resiliency, Limits, and Moral Hazards in Software Engineering (LambdaConf 2024)
chriskrycho
0
440
FoodGram
iseruuuuu
0
230
PHPコードの実行モデルを理解する / Understanding-the-PHP-Execution-Model
shin1x1
0
1.1k
Implementing Design Systems in Swift
seyfoyun
2
530
ServerAction で Progressive Enhancement はどこまで頑張れるか? / progressive-enhancement-with-server-action
takefumiyoshii
6
520
Featured
See All Featured
10 Git Anti Patterns You Should be Aware of
lemiorhan
649
58k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
228
16k
Building Applications with DynamoDB
mza
88
5.7k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
14
8.4k
Web Components: a chance to create the future
zenorocha
306
41k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
323
20k
5 minutes of I Can Smell Your CMS
philhawksworth
199
19k
How to name files
jennybc
65
94k
Designing Dashboards & Data Visualisations in Web Apps
destraynor
226
51k
Building Better People: How to give real-time feedback that sticks.
wjessup
356
18k
We Have a Design System, Now What?
morganepeng
43
6.8k
The Cost Of JavaScript in 2023
addyosmani
21
4k
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