SlideShare a Scribd company logo
1 of 11
Download to read offline
JUnit and Mockito tips
Mockito annotations
• @Mock
• @InjectMocks
• @Captor
Example production code
class MailServer {
void send(String smtpMessage) throws IOException {
// Opens a connection to a SMTP server, sends smtpMessage
}
}
class Messenger {
private final MailServer mailServer;
Messenger(MailServer mailServer) {
this.mailServer = mailServer;
}
void sendMail(String from, String to, String body) {
String smtpMessage = String.join("n", "From: " + from, "To: " + to, "", body);
try {
mailServer.send(smtpMessage);
} catch (IOException e) {
throw new UncheckedIOException("Error! smtpMessage=" + smtpMessage, e);
}
}
}
Test without Mockito annotations
class MessengerPlainTest {
MailServer mailServer;
Messenger sut;
@BeforeEach
void setUp() {
mailServer = Mockito.mock(MailServer.class);
sut = new Messenger(mailServer);
}
@Test
@DisplayName("Messenger constructs the SMTP message and feeds MailServer")
void test() throws IOException {
String expected = "From: joe@example.comn"
+ "To: jane@example.comnn"
+ "Hello!";
sut.sendMail("joe@example.com", "jane@example.com", "Hello!");
Mockito.verify(mailServer).send(expected);
}
}
Test with @Mock
@ExtendWith(MockitoExtension.class)
class MessengerTest {
@Mock
MailServer mailServer;
@InjectMocks
Messenger sut;
@Test
@DisplayName("Messenger constructs the SMTP message and feeds MailServer")
void test() throws IOException {
String expected = "From: joe@example.comn"
+ "To: jane@example.comnn"
+ "Hello!";
sut.sendMail("joe@example.com", "jane@example.com", "Hello!");
Mockito.verify(mailServer).send(expected);
}
}
Avoid unchecked assignment warning with
@Mock
Consumer<String> consumer = Mockito.mock(Consumer.class);
// The above yields:
Warning:(35, 49) java: unchecked conversion required:
java.util.function.Consumer<java.lang.String> found: java.util.function.Consumer
// Solution:
@ExtendWith(MockitoExtension.class)
class MyTest {
@Mock
Consumer<String> consumer;
...
Test with @Captor
@ExtendWith(MockitoExtension.class)
class MessengerCaptorTest {
@Mock
MailServer mailServer;
@InjectMocks
Messenger sut;
@Captor
ArgumentCaptor<String> captor;
@Test
@DisplayName("Messenger constructs the SMTP message and feeds MailServer")
void test() throws IOException {
sut.sendMail("joe@example.com", "jane@example.com", "Hello!");
Mockito.verify(mailServer).send(captor.capture());
String capturedValue = captor.getValue();
assertTrue(capturedValue.endsWith("Hello!"));
}
}
AssertJ
• A modern assertion library for unit tests written in Java
• Provides better readability and richer assertions than old equivalents
• https://assertj.github.io/doc/#assertj-overview
AssertJ examples (taken from here)
// basic assertions
assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron);
// chaining string specific assertions
assertThat(frodo.getName()).startsWith("Fro")
.endsWith("do")
.isEqualToIgnoringCase("frodo");
// collection specific assertions (there are plenty more)
// in the examples below fellowshipOfTheRing is a
List<TolkienCharacter>
assertThat(fellowshipOfTheRing).hasSize(9)
.contains(frodo, sam)
.doesNotContain(sauron);
AssertJ example for an unhappy path
@ExtendWith(MockitoExtension.class)
class MessengerUnhappyTest {
@Mock
MailServer mailServer;
@InjectMocks
Messenger sut;
@Test
@DisplayName("Messenger throws UncheckedIOException with the SMTP message when MailServer has thrown IOException")
void test() throws IOException {
doThrow(new IOException("The server is down")).when(mailServer).send(any());
String expectedMessage = "From: joe@example.comn"
+ "To: jane@example.comnn"
+ "Hello!";
assertThatThrownBy(() -> sut.sendMail("joe@example.com", "jane@example.com", "Hello!"))
.isInstanceOf(UncheckedIOException.class)
.hasMessage("Error! smtpMessage=%s", expectedMessage)
.hasCauseInstanceOf(IOException.class);
}
}
Conclusion
• We’ve discussed some tips about
• Mockito annotations
• Basic usages of AssertJ
• Recommended further reading:
• Mockito framework site
• AssertJ - fluent assertions java library
• Practical Unit Testing: JUnit 5, Mockito, TestNG, AssertJ - book by Tomek
Kaczanowski
• Code used in the slides: https://github.com/nuzayats/junittips

More Related Content

What's hot (10)

Mule esb using file to string and logger component
Mule esb using file to string and logger componentMule esb using file to string and logger component
Mule esb using file to string and logger component
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Mule hppt java
Mule hppt javaMule hppt java
Mule hppt java
 
Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
 
Mxunit
MxunitMxunit
Mxunit
 
Spock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationSpock Testing Framework - The Next Generation
Spock Testing Framework - The Next Generation
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Server1
Server1Server1
Server1
 
Servlet lifecycle
Servlet  lifecycleServlet  lifecycle
Servlet lifecycle
 

Similar to JUnit and Mockito tips

香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
biyu
 
Baocao Web Tech Java Mail
Baocao Web Tech Java MailBaocao Web Tech Java Mail
Baocao Web Tech Java Mail
xicot
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
ksain
 
Note Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdfNote Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdf
fatoryoutlets
 
Multi client
Multi clientMulti client
Multi client
Aisy Cuyy
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambar
yoyomay93
 
Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)
Rara Ariesta
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
Ted Pennings
 

Similar to JUnit and Mockito tips (20)

Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 
Baocao Web Tech Java Mail
Baocao Web Tech Java MailBaocao Web Tech Java Mail
Baocao Web Tech Java Mail
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Testing in android
Testing in androidTesting in android
Testing in android
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17
 
Note Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdfNote Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdf
 
Multi client
Multi clientMulti client
Multi client
 
Send email
Send emailSend email
Send email
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambar
 
Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017
 
Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
Web based development
Web based developmentWeb based development
Web based development
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdf
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 

More from Kohei Nozaki (6)

The State Pattern
The State PatternThe State Pattern
The State Pattern
 
Synchronize access to shared mutable data
Synchronize access to shared mutable dataSynchronize access to shared mutable data
Synchronize access to shared mutable data
 
The Singleton Pattern In Java
The Singleton Pattern In JavaThe Singleton Pattern In Java
The Singleton Pattern In Java
 
Favor composition over inheritance
Favor composition over inheritanceFavor composition over inheritance
Favor composition over inheritance
 
Java Generics wildcards
Java Generics wildcardsJava Generics wildcards
Java Generics wildcards
 
Overview of Java EE
Overview of Java EEOverview of Java EE
Overview of Java EE
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

JUnit and Mockito tips

  • 2. Mockito annotations • @Mock • @InjectMocks • @Captor
  • 3. Example production code class MailServer { void send(String smtpMessage) throws IOException { // Opens a connection to a SMTP server, sends smtpMessage } } class Messenger { private final MailServer mailServer; Messenger(MailServer mailServer) { this.mailServer = mailServer; } void sendMail(String from, String to, String body) { String smtpMessage = String.join("n", "From: " + from, "To: " + to, "", body); try { mailServer.send(smtpMessage); } catch (IOException e) { throw new UncheckedIOException("Error! smtpMessage=" + smtpMessage, e); } } }
  • 4. Test without Mockito annotations class MessengerPlainTest { MailServer mailServer; Messenger sut; @BeforeEach void setUp() { mailServer = Mockito.mock(MailServer.class); sut = new Messenger(mailServer); } @Test @DisplayName("Messenger constructs the SMTP message and feeds MailServer") void test() throws IOException { String expected = "From: joe@example.comn" + "To: jane@example.comnn" + "Hello!"; sut.sendMail("joe@example.com", "jane@example.com", "Hello!"); Mockito.verify(mailServer).send(expected); } }
  • 5. Test with @Mock @ExtendWith(MockitoExtension.class) class MessengerTest { @Mock MailServer mailServer; @InjectMocks Messenger sut; @Test @DisplayName("Messenger constructs the SMTP message and feeds MailServer") void test() throws IOException { String expected = "From: joe@example.comn" + "To: jane@example.comnn" + "Hello!"; sut.sendMail("joe@example.com", "jane@example.com", "Hello!"); Mockito.verify(mailServer).send(expected); } }
  • 6. Avoid unchecked assignment warning with @Mock Consumer<String> consumer = Mockito.mock(Consumer.class); // The above yields: Warning:(35, 49) java: unchecked conversion required: java.util.function.Consumer<java.lang.String> found: java.util.function.Consumer // Solution: @ExtendWith(MockitoExtension.class) class MyTest { @Mock Consumer<String> consumer; ...
  • 7. Test with @Captor @ExtendWith(MockitoExtension.class) class MessengerCaptorTest { @Mock MailServer mailServer; @InjectMocks Messenger sut; @Captor ArgumentCaptor<String> captor; @Test @DisplayName("Messenger constructs the SMTP message and feeds MailServer") void test() throws IOException { sut.sendMail("joe@example.com", "jane@example.com", "Hello!"); Mockito.verify(mailServer).send(captor.capture()); String capturedValue = captor.getValue(); assertTrue(capturedValue.endsWith("Hello!")); } }
  • 8. AssertJ • A modern assertion library for unit tests written in Java • Provides better readability and richer assertions than old equivalents • https://assertj.github.io/doc/#assertj-overview
  • 9. AssertJ examples (taken from here) // basic assertions assertThat(frodo.getName()).isEqualTo("Frodo"); assertThat(frodo).isNotEqualTo(sauron); // chaining string specific assertions assertThat(frodo.getName()).startsWith("Fro") .endsWith("do") .isEqualToIgnoringCase("frodo"); // collection specific assertions (there are plenty more) // in the examples below fellowshipOfTheRing is a List<TolkienCharacter> assertThat(fellowshipOfTheRing).hasSize(9) .contains(frodo, sam) .doesNotContain(sauron);
  • 10. AssertJ example for an unhappy path @ExtendWith(MockitoExtension.class) class MessengerUnhappyTest { @Mock MailServer mailServer; @InjectMocks Messenger sut; @Test @DisplayName("Messenger throws UncheckedIOException with the SMTP message when MailServer has thrown IOException") void test() throws IOException { doThrow(new IOException("The server is down")).when(mailServer).send(any()); String expectedMessage = "From: joe@example.comn" + "To: jane@example.comnn" + "Hello!"; assertThatThrownBy(() -> sut.sendMail("joe@example.com", "jane@example.com", "Hello!")) .isInstanceOf(UncheckedIOException.class) .hasMessage("Error! smtpMessage=%s", expectedMessage) .hasCauseInstanceOf(IOException.class); } }
  • 11. Conclusion • We’ve discussed some tips about • Mockito annotations • Basic usages of AssertJ • Recommended further reading: • Mockito framework site • AssertJ - fluent assertions java library • Practical Unit Testing: JUnit 5, Mockito, TestNG, AssertJ - book by Tomek Kaczanowski • Code used in the slides: https://github.com/nuzayats/junittips