链接OngoingStubbing Mockito的使用?

问题描述 投票:0回答:1

在Mockito中,当我们尝试模拟方法调用时,假设我们配置了类似的东西

when(exampleClass.getOutputString(anyString())).thenReturn("output1");

这都是可以理解的。但是我的问题是,此thenReturn("output1")方法返回OngoingStrubbing对象的原因(与when(exampleClass.getOutputString(anyString()))方法返回的对象相同)是什么原因,以便我们可以执行以下操作

when(exampleClass.getOutputString(anyString())).thenReturn("output1").thenReturn("output2");

when(exampleClass.getOutputString(anyString())).thenReturn("output1").thenThrow(new IllegalArgumentException());

但是,以上两种情况,在使用模拟程序时,仅返回"output1",仅此而已。谁知道,为什么存在此链接功能,它的用途是什么?同样的事情也适用于doReturn()

java unit-testing mocking mockito powermock
1个回答
1
投票

这意味着对于第一个调用,它给出了ouput1,在第二个调用中给出了output2,依此类推。

when(exampleClass.getOutputString(anyString())).thenReturn("output1").thenReturn("output2");

,您需要在目标测试课程中达到一个条件的第二个条件,所以给出

第一种情况下是[output1,但第二种情况下您想测试失败]

try-catch子句或查看代码是否涵盖了破碎的场景,例如异常

when(exampleClass.getOutputString(anyString())).thenReturn("output1").thenThrow(new IllegalArgumentException());

© www.soinside.com 2019 - 2024. All rights reserved.