Issue
I am writing unit tests using JUnit5 and Mockito for a class Main.java
.
The dependency class ExternalApi.java
is injected in Main.java
.
@ExtendWith(MockitoExtension.class)
public class MainTest {
@InjectMocks
Main main;
@Mock
ExternalApi externalApi;
@Test
void testAbcMethod() {
}
}
The abc() method in Main.java
calls externalApi.doSomething()
which does some stuff.
I don't want this original externalApi method to be called in my test. Do I need to define
doNothing().when(externalApi).when(doSomething());
or is it just enough to mock ExternalApi
?
What happens when we don't define what happens when we call a mocked object's methods?
Solution
What happens when we don't define what happens when we call a mocked object's methods?
Nothing happens. Mocking is enough since it's not the real class/method that is called but the mocked one.
If you had spied on the instance, that would have triggered the real method call. Only then, you'd have thought of using doNothing
to silence the method behavior.
@Test
public void whenNotDefineBehaviorOnMock_thenCorrect() {
List mockList = Mockito.mock(ArrayList.class);
// No behavior defined,
mockList.add("one");
Mockito.verify(mockList).add("one");
// Size is still empty
assertEquals(0, mockList.size());
// Behavior defined
Mockito.when(mockList.size()).thenReturn(100);
assertEquals(100, mockList.size());
}
Answered By - exaucae
Answer Checked By - Katrina (JavaFixing Volunteer)