有没有一种方法可以让Mockito在一个方法调用返回值时执行doNothing()方法

5

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

例如:

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

现在我想以某种方式使用mockito,使得这个otherService.getList(Employee)什么也不做,只是跳过这一个执行。

我相信你可以为otherService创建一个模拟对象,然后做类似于when(otherService.getList(someargs)).doNothing()的操作。具体语法我记不清了。 - Siddhartha
2
如果otherService是一个mock的引用,那么这已经是默认行为(并且返回null)。 - Sotirios Delimanolis
更正:Mockito 的默认行为是返回一个空列表。 - Stefan Birkner
2个回答

2
如果您已经注入了模拟的 otherService,那么在 otherService.getList(Employee.class) 中的所有方法调用都将默认返回一个空的 List,除非您明确告诉 Mockito 如果它们不是 void 方法,则使用 thenReturn 返回某些内容。它取决于 getList 方法中的业务流程会返回什么。
简而言之,明确告诉 Mockito 在 getList 方法中所有方法调用应该做什么,以便返回值符合您的预期。

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

这只是改变了返回值,但方法仍然会执行。 - mudit_sen
@mudit_sen 并不是这样的,Mockito 会创建一个代理类,如果方法签名与模拟配置匹配,则不会调用真实方法,而是调用 Mockito 的代理类。您可能会混淆其他注释 @Spy,它使用真实对象。 - Federico Piazza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接