有人可以为我提供一种使用 Mockito 测试以下代码的方法吗?我目前收到 MissingMethodInvocation 异常。
obj1.getId().getString()
obj1 是一个模拟对象,getId() 方法通过 getString() 方法返回另一个对象 obj2。我努力了
@Mock private obj1
@Mock private obj2
Mockito.when(obj1.getId()).thenReturn(obj2);
Mockito.when(obj2.getString()).thenReturn("TEST STRING");
但是,我收到以下错误
<<< ERROR!
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
It is a limitation of the mock engine.
并尝试
@Mock private obj1
@Mock private obj2
Mockito.when(obj1.getId().getString()).thenReturn("TEST STRING");
返回
<<< ERROR!
java.lang.NullPointerException: null
提前感谢您的任何帮助或参考。
解决方案 obj2.getString() 是一种最终方法,正如错误读数所说 - “1. 你存根:final/private/equals()/hashCode() 方法中的任何一个。这些方法不能被存根/验证。”
我的解决方法是设置 obj2 的字符串 -
@Mock private Obj1Type obj1
Mockito.when(obj1.getId()).thenReturn(obj2);
obj2.setString("TEST_STRING");