mockito exception WrongTypeOfReturnValue "Optional cannot be returned by getInfo3(), getInfo3() shou



我在测试中遇到一个异常,mockito认为getInfo3((返回一个Optional,但返回类型是List<gt;。

mockito测试:

@Test
public void searchUser() {
when(mockUserDao.getInfo1(anyInt())).thenReturn(Optional.of(info));
when(mockUserDao.getInfo2(anyInt())).thenReturn(Optional.of(info1));
when(mockUserDao.getInfo3(anyInt())).thenReturn(new ArrayList<>());
when(userAPI.getUserById(anyInt())).thenReturn(Optional.of(fullUser));
....
}

getInfo3((

@SqlQuery("SELECT * FROM info where id = :uid")
List<Info3> getInfo3(@Bind("uid") Integer userId);

getUserById((

public Optional<RootUser> getUserById(Integer userId) {
Optional<Info1> info1 = this.userDao.getInfo1(userId);
Optional<Info2> info2 = this.userDao.getInfo2(userId);
List<Info3> info3 = this.userDao.getInfo3(userId);
...
return Optional.of(RootUser.builder()
.setInfo1(info1)
.setInfo2(info2)
.setInfo3(info3)
.setInfo4(info4)
.build());
}

以下是运行测试后的错误输出,测试失败时(userAPI.getUserById(anyInt(((.thenReturn(Optional.of(fullUser((:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Optional cannot be returned by getInfo3()
getInfo3() should return List
***
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.

这不是一个多线程测试。非常感谢您的任何建议!

下面一行是导致我的测试失败的额外mock。删除此项后,异常就消失了。

when(userAPI.getUserById(anyInt())).thenReturn(Optional.of(fullUser));

最新更新