当方法调用实际返回某些东西时,有没有办法让Mockito doNothing()

时间:2015-10-05 21:27:48

标签: java junit mockito

所以我有这个方法在内部调用另一个服务,为了我的测试目的,我不关心这个内部调用,我不希望这个内部服务做任何事情。

例如

public void testMyMethod() {
        List<String> strings = otherService.getList(Employee);
}

现在我想以这个otherService.getList(Employee)不做任何事情的方式使用mockito。它只是跳过了这个的执行。

2 个答案:

答案 0 :(得分:1)

您可以使用whenthenReturn作为正常测试。

例如,您可以使用以下代码:

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);
    }
}

答案 1 :(得分:1)

如果你已经注入了mock otherService,那么otherService.getList(Employee.class)中的所有方法调用都会返回一个空的List作为默认值,除非你明确告诉Mockito只返回一些内容(使用thenReturn)他们不是无效的方法。这取决于getList方法中的业务流程,它将返回什么。

TLDR,明确告诉Mockito如何对getList方法中的所有方法调用做什么,以便返回值符合您的期望。

相关问题