我有一个方法,它内部调用了另一个服务,在我的测试中我不关心这个内部调用和我不希望这个内部服务做任何事情。
例如:
public void testMyMethod() {
List<String> strings = otherService.getList(Employee);
}
现在我想以某种方式使用mockito,使得这个
otherService.getList(Employee)
什么也不做,只是跳过这一个执行。otherService.getList(Employee.class)
中的所有方法调用都将默认返回一个空的 List
,除非您明确告诉 Mockito 如果它们不是 void 方法,则使用 thenReturn
返回某些内容。它取决于 getList 方法中的业务流程会返回什么。when
和thenReturn
。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);
}
}
@Spy
,它使用真实对象。 - Federico Piazza
when(otherService.getList(someargs)).doNothing()
的操作。具体语法我记不清了。 - SiddharthaotherService
是一个mock的引用,那么这已经是默认行为(并且返回null
)。 - Sotirios Delimanolis