Java Mockito when().thenReturn() 不能正常工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33125769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:21:35  来源:igfitidea点击:

Mockito when().thenReturn() doesn't work properly

javaunit-testingmockingmockito

提问by tamird14

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.

我有一个带有 2 个函数的 A 类:函数 a() 返回一个随机数。函数 b() 调用 a() 并返回返回的值。

In a test I wrote this:

在测试中我写了这个:

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

要清楚 - 这不是我真正的代码,而是一个简单的代码来解释我的问题

采纳答案by Sajan Chandran

Since class Ais mocked, all method invocations wont go to the actual object. Thats why your second assert fails (i guess it might have returned 0).

由于类A是模拟的,所有方法调用都不会转到实际对象。这就是为什么你的第二个断言失败(我猜它可能已经返回 0)。

Solution:

解决方案:

You could do something like

你可以做类似的事情

when(test.b()).thenCallRealMethod();

else you could spylike

否则你会spy喜欢

A test = spy(new A());
Mockito.when(test.a()).thenReturn(35);
assertEquals(35,test.a());
assertEquals(35,test.b());

回答by weston

function b() which calls a()

函数 b() 调用 a()

Maybe it does in your actual concrete A, but that is not being used in this case. Only the mock is being used here.

也许它在您的实际混凝土中确实如此A,但在这种情况下并未使用。这里只使用模拟。

So you need to tell the mock what to do for every method you want to call:

所以你需要告诉 mock 对你想要调用的每个方法做什么:

Mockito.when(test.b()).thenReturn(35);

回答by Jens

Because you have only a mock when you call it with test.a().

因为当你用 test.a() 调用它时,你只有一个模拟。

You have to add Mockito.when(test.b()).thenReturn(35). then your code works fine

你必须添加Mockito.when(test.b()).thenReturn(35). 那么你的代码工作正常