我正在JUnit中调用一个公共方法,而跳过对由公共方法调用的私有方法的调用。
SampleService sampleServiceSpy = Mockito.spy(sampleService); // I have reference to it through @InjectMocks
String str = Mockito.doReturn("Hiii").when(sampleServiceSpy ).sendRequestToAnotherComponent(<ARG1>,"?",<ARG3>);
String res = sampleServiceSpy.processRequest(<ARG1>, <ARG2>);
这里processRequest()
是公共方法,私有方法是sendRequestToAnotherComponent()
,我要跳过,但问题是此方法期望第二个参数作为目录路径,它是随机生成的UUID,因此每次都不相同嘲笑它。 (在示例代码中显示为?
)
有什么办法可以传递任何值并可以跳过此方法?
我检查了Mockito.anyString()
是用来创建模拟对象的,因此不能在此测试用例中使用它。
答案 0 :(得分:1)
要回答您的直接问题-使用匹配器-例如:
Mockito.doReturn("Hiii").when(sampleServiceSpy).sendRequestToAnotherComponent(eq(<ARG1>),any(UUID.class), eq(<ARG3>));
但是,不要尝试模拟正在测试的类的方法,而是注入其他组件的模拟。这样,测试可以verify()
调用其他组件。