Mockito异常WrongTypeOfReturnValue“可选不能由getInfo3返回,getInfo3应该返回List”

问题描述

我在测试中遇到了一个异常,其中Mockito认为getInfo3()返回的是Optional,但是返回类型是List 。

模拟测试:

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

这不是多线程测试。任何建议都非常感谢!

解决方法

以下一行是一个额外的模拟,导致我的测试失败。删除此异常后,该异常消失了。

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...