Junit Mockito测试:零相互作用



我想使用Junit和Mockito测试此对象列表。

如果循环是如此:

       List<Message> owner = new ArrayList<>();
   for (int i = 0; i < messageStorage.getMessage(us.getName()).size(); i++) {
            owner.add(new Message(us.getName() + " - " + messageStorage.getMessage(us.getName()).get(i).getText(),
                    messageStorage.getMessage(us.getName()).get(i).getTime()));
        }
    listOfMessages.addAll(owner);

Mockito中的测试正常工作!

@Test
public void onTheWallTest() {
    when(clock.now()).thenReturn(parse("2014-12-03T10:15:30.00Z"));
    User follows = new User("someFollower");
    Mockito.when(userStorage.getUser(Matchers.anyString())).thenReturn(follows);
    wall.onTheWall();
    Mockito.verify(messageStorage).getMessage("someFollower");
}

当我以这种方式使用foreach/lambda时:

 IntStream.range(0, owner.size())
                .forEach(i ->
                        owner.add(new Message(us.getName() + " - " + messageStorage.getMessage(us.getName()).get(i).getText(),
                                messageStorage.getMessage(us.getName()).get(i).getTime()))
                );
        listOfMessages.addAll(owner);

测试因响应而失败:

    Wanted but not invoked:
messageStorage.getMessage("someFollower");
-> at app.command.WallTest.onTheWallTest(WallTest.java:47)
Actually, there were zero interactions with this mock.

我修复了:

messageStorage.getMessage(us.getName())
              .stream()
              .map(item -> owner.add(
                  new Message(us.getName() + " - " + item.getText(), item.getTime())
              ));

相关内容

  • 没有找到相关文章

最新更新