首页 > 解决方案 > org.mockito.exceptions.misusing.WrongTypeOfReturnValue

问题描述

我正在尝试执行单元测试,但遇到 Iterable 异常

实现代码

private ClientWrapper clientWrapper;

Iterable<Document> documentIterable=clientWrapper.doOperation(reqList);

测试代码

@Mock
ClientWrapperImpl mocClientWrapper;

Document mockDocuent=Mockito.mock(Document.class);

Iterable<Document>  documentIterable=Mockito.mock(Iterable.class);
Iterator<Document> documentIterator=Mockito.mock(Iterator.class);
Mockito.when(documentIterable.iterator)).thenReturn(documentIterator);
Mockito.when(documentIterator.hasNext()).thenReturn(true).thenReturn(false);
Mockito.when(documentIterator.next()).thenReturn(mockDocuent);

Mockito.when(mocClientWrapper.doOperation(Mockito.anyList())).thenReturn(documentIterable);

我得到的例外:Full StackTrace

org.mockito.exceptions.misusing.WrongTypeOfReturnValue
Iterable$MockitoMock$598 cannot be returned by toString()
toString() should return string

If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1.This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2.A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies-- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

这个异常显示在我正在模拟 doOperation 方法的测试类中。

标签: javajunitmockito

解决方案


推荐阅读