This document provides an overview of how to use Mockito to create mock objects and define their behavior in tests.
It explains how to create mocks with mock(ClassToMock.class), define return values and exceptions with when(method()).thenReturn()/thenThrow(), and verify mock interactions with verify(mock).method(). It also covers using @Mock annotation and initMocks() to initialize mocks, and matchers like eq() to verify argument matching. The document concludes with some Eclipse IDE tips to help with Mockito development.
2. This work by
Fredrik Wendt
is licensed under a
Creative Commons
Attribution-NonCommercial-ShareAlike
3.0 Unported License
http://creativecommons.org/licenses/by-nc-sa/3.0/
18. The IDE Can Help 1
• Window » Preferences » Java »
Editor » Content Assistant » Favorites
● org.junit.Assert.* assertTrue()
● org.mockito.Mockito.* mock()
● org.mockito.MockitoAnnotations @Mock
● org.mockito.BDDMockito.* given().then*()
19. The IDE Can Help 2
• Window » Preferences » Java » Editor » Templates
${staticImport:importStatic(
'org.mockito.MockitoAnnotations.
initMocks')}
@${beforeAnnotation:
newType(org.junit.Before)}
public void ${setUp}() {
initMocks(this);
${cursor}
}
20. The IDE Can Help 3
• Window » Preferences » Java » Editor » Templates
tdd
@Test
public void ${test} throws Exception {
// Arrange
// Act
// Assert
}
21. public class EmptyMatcher extends
TypeSafeMatcher<Collection <?>> {
@Override
public boolean matchesSafely(Collection<?> c) {
return c.isEmpty();
}
public void describeTo(Description desc) {
desc.appendText("empty");
}
@Factory
public static <T>
Matcher<? super Collection<?>> isEmpty() {
return new EmptyMatcher();
}
}
Editor's Notes
out of reach:
* too hard to setup
* Singletons
* Interfaces without proper classes