Mockito when().thenReturn() 不能正常工作 [英] Mockito when().thenReturn() doesn't work properly
本文介绍了Mockito when().thenReturn() 不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有 2 个功能的 A 类:函数 a() 返回一个随机数.函数 b() 调用 a() 并返回返回的值.
I have a class A with 2 functions: function a() which returns a random number. function b() which calls a() and return the value returned.
在测试中我写了这个:
A test = Mockito.mock(A.class)
Mockito.when(test.a()).thenReturn(35)
assertEquals(35,test.a())
assertEquals(35,test.b())
测试在第二个断言处失败.有谁知道为什么?
The test fails at the second assert. Does anyone know why?
要清楚 - 这不是我真正的代码,而是一个简单的代码来解释我的问题
To be clear - this is not my real code, but a simple code to explain my problem
推荐答案
由于类 A
是模拟的,因此所有方法调用都不会转到实际对象.这就是你的第二个断言失败的原因(我猜它可能返回了 0).
Since class A
is mocked, all method invocations wont go to the actual object.
Thats why your second assert fails (i guess it might have returned 0).
解决方案:
你可以做类似的事情
when(test.b()).thenCallRealMethod();
否则你可以spy
喜欢
A test = spy(new A());
Mockito.when(test.a()).thenReturn(35);
assertEquals(35,test.a());
assertEquals(35,test.b());
这篇关于Mockito when().thenReturn() 不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文