【问题标题】:mockito exception WrongTypeOfReturnValue "Optional cannot be returned by getInfo3(), getInfo3() should return List"mockito 异常 WrongTypeOfReturnValue “getInfo3() 不能返回可选,getInfo3() 应该返回 List”
【发布时间】:2020-09-29 20:01:03
【问题描述】:

我在测试中遇到了一个异常,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());
    }

这是运行测试后的错误输出,测试失败 when(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.

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

【问题讨论】:

    标签: java mockito dao


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多