Reputation: 521
So I have this method that internally calls another service and for my testing purpose I dont care about this internal call and I dont want this internal service to do anything.
For e.g.
public void testMyMethod() {
List<String> strings = otherService.getList(Employee);
}
Now I would like to use mockito in a way that this otherService.getList(Employee) does not do anything. It simply skips the execution for this one.
Upvotes: 7
Views: 14708
Reputation: 191
If you already inject mock otherService, all the method calls in otherService.getList(Employee.class)
will return an empty List
as default unless you explicitly tell Mockito to return something (by using thenReturn
) only if they are not void method. It depends on the business process in the getList
method about what will it return.
TLDR, explicitly tell Mockito what to do for all method calls in the getList
method so that the return value will meet your expectation.
Upvotes: 2
Reputation: 31045
You can use when
and thenReturn
as a normal test.
For instance, you can have this code:
public class Test
{
private OtherService otherService;
public void doSomething() {
otherService.getList(new Employee("X"));
}
/* Getters/Setters/Contructors */
}
@RunWith(MockitoJUnitRunner.class)
public class MyTest
{
@Mock
private OtherService otherService;
@InjectMocks
private Test test; // Test uses 'otherService' internally
@Test
public void testVoid()
{
test.doSomething(); // 'test' do something and it also invokes your otherService
// Mock your otherService method to return null (or whatever you want)
when(otherService.getList(any(Employee.class))).thenReturn(null);
}
}
Upvotes: 1