错误细节:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Boolean cannot be returned by updateItemAttributesByJuId()
updateItemAttributesByJuId() should return ResultRich
This exception might occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
Run Code Online (Sandbox Code Playgroud)
我的代码:
@InjectMocks
protected ItemArrangeManager arrangeManagerSpy = spy(new ItemArrangeManagerImpl());
@Mock
protected JuItemWriteService juItemWriteService;
when(arrangeManagerSpy
.updateItemAttributes(mapCaptor.capture(), eq(juId), eq(itemTO.getSellerId())))
.thenReturn(false);
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我呼吁when
对updateItemAttributes
(它返回boolean
)不是updateItemAttributesByJuId
.
boolean
从updateItemAttributesByJuId
?小智 165
根据https://groups.google.com/forum/?fromgroups#!topic/mockito/9WUvkhZUy90,你应该改写你的
when(bar.getFoo()).thenReturn(fooBar)
Run Code Online (Sandbox Code Playgroud)
至
doReturn(fooBar).when(bar).getFoo()
Run Code Online (Sandbox Code Playgroud)
对我来说,这意味着我正在运行:
a = Mockito.mock(SomeClass.class);
b = new RealClass();
when(b.method1(a)).thenReturn(c);
// within this method1, it calls param1.method2() -- note, b is not a spy or mock
Run Code Online (Sandbox Code Playgroud)
所以发生的事情是,mockito 检测到a.method2()
正在调用的,并告诉我我无法c
从a.method2()
哪个错误中返回。
修复:使用doReturn(c).when(b).method1(a)
样式语法(而不是when(b.method1(a)).thenReturn(c);
),这将帮助您更简洁快速地发现隐藏的错误。
或者在这种特殊情况下,在这样做之后,它开始显示更准确的“NotAMockException”,我将其更改为不再尝试从非模拟对象设置返回值。
非常感兴趣的问题。就我而言,这个问题是在我尝试在以下类似行上调试测试时引起的:
Boolean fooBar;
when(bar.getFoo()).thenReturn(fooBar);
Run Code Online (Sandbox Code Playgroud)
重要的注意事项是测试在没有调试的情况下可以正确运行。
无论如何,当我用下面的代码片段替换上面的代码时,我便能够毫无问题地调试问题行。
doReturn(fooBar).when(bar).getFoo();
Run Code Online (Sandbox Code Playgroud)
我有这个错误,因为在我的测试中我有两个期望,一个在模拟上,一个在具体类型上
MyClass cls = new MyClass();
MyClass cls2 = Mockito.mock(Myclass.class);
when(foo.bar(cls)).thenReturn(); // cls is not actually a mock
when(foo.baz(cls2)).thenReturn();
Run Code Online (Sandbox Code Playgroud)
我通过将 cls 也更改为模拟来修复它