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

时间:2022-08-10 19:40:26

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类:函数a(),它返回一个随机数。函数b(),它调用一个()并返回返回的值。

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

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

3 个解决方案

#1


17  

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).

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

Solution:

解决方案:

You could do something like

你可以做一些类似的事情。

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

else you could spy like

你还可以像间谍一样。

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

#2


3  

function b() which calls a()

函数b(),它调用()

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中,但是在这个例子中没有用到。这里只使用了mock。

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

因此,您需要告诉mock对于您想要调用的每个方法要做什么:

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

#3


3  

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

因为当你用test来调用它时,你只有一个mock。

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

你必须添加Mockito.when(test.b()),然后返回(35)。这样你的代码就可以正常工作了。

#1


17  

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).

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

Solution:

解决方案:

You could do something like

你可以做一些类似的事情。

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

else you could spy like

你还可以像间谍一样。

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

#2


3  

function b() which calls a()

函数b(),它调用()

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中,但是在这个例子中没有用到。这里只使用了mock。

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

因此,您需要告诉mock对于您想要调用的每个方法要做什么:

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

#3


3  

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

因为当你用test来调用它时,你只有一个mock。

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

你必须添加Mockito.when(test.b()),然后返回(35)。这样你的代码就可以正常工作了。