Search code examples
javaunit-testingjava-streamspock

Different expectations during mocking


I'm testing the filtering of my messages. It will only save the message if the id does not exist yet.

List<Message> messages = ninitializedDto.stream()
        .filter(message -> !messageRepository.existsById(message.getId())
        .map(this::initializeMessage)
        .collect(Collectors.toList());

return messageRepository.saveAll(messages);

But in my Spock test, the size always returns 1. (Even though I printed the messages.size() before the return (it returns 0)

def "createMessages should filter and save only messages that does not exist yet"() {
        given:
        UninitializedDto dto = Mock()
        dto.getId() >> 2L

        List<UninitializedDto> messageDtos = [dto]

        messageRepository.existsById(dto.getId()) >> true

        when:
        initialize.createMessages(messageDtos)

        then:
        1 * messageRepository.saveAll(_) >> {
            List<Message> savedMessageList ->
                assert savedMessageList.size() == 0
        }
    }

Solution

  • Figured it out. There's a bug that wraps the list argument in another list.

    1 * messageRepository.saveAll(_) >> {
        List<Message> savedMessageList ->
        List<Message> messageList = savedMessageList.get(0) as List<Message>
    
        assert savedMessageList.size() == 0
    }