The document provides tips and examples for using Mockito and AssertJ libraries for unit testing in Java. It describes Mockito annotations like @Mock, @InjectMocks, and @Captor that simplify mocking objects. It shows how to write tests with and without these annotations. It also demonstrates how to make assertions with AssertJ's fluent API for readability and richer assertions compared to JUnit assertions. Examples include testing both happy and unhappy paths as well as capturing arguments with @Captor.
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