有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java mockito异常ErrorTypeOfReturnValue“getInfo3()无法返回可选值,getInfo3()应返回列表”

我在测试中遇到了一个异常,mockito认为getInfo3()返回的是可选的,但返回的类型是列表<>

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())。然后返回(可选。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.

这不是一个多线程测试。任何建议都将不胜感激


共 (1) 个答案

  1. # 1 楼答案

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

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