0

我正在尝试测试我的服务,当我执行 assertEquals 时,我收到了一个错误

这是我的测试

@Test
    public void createNewCommentCreatesNewDTOIfNoDTOExists() {
        CommentDTO commentDTO = mock(CommentDTO.class);
        MergedScopeKey mergedScopeKey = mock(MergedScopeKey.class);

        //set merged scope key
        sut.setInput(mergedScopeKey);
        String commentText = "commentText";

        //define behaviour
        when(commentApplicationService.createCommentDTO(mergedScopeKey, commentText)).thenReturn(commentDTO);

        sut.createNewComment(commentText);

        //test the functionality
        assertNotNull(commentDTO);
        assertEquals(commentText, commentDTO.getCommentText());

        //test the behavior
        verify(commentApplicationService).createCommentDTO(mergedScopeKey, commentText);

    }

这是我想测试的方法:

protected void createNewComment(String commentText) {

        CommentDTO commentDTO = commentApplicationService.getDTOComment(mergedScopeKey);
        if (commentDTO == null) {
            commentApplicationService.createCommentDTO(mergedScopeKey, commentText);
        } else {
            updateComment(commentDTO, commentText);
        }

    }

你有什么想法我做错了吗?

4

1 回答 1

1

您定义行为:

when(commentApplicationService.createCommentDTO(mergedScopeKey, commentText)).thenReturn(commentDTO);

但是在您的测试中,您调用:

CommentDTO commentDTO = commentApplicationService.getDTOComment(mergedScopeKey);

这是一种不同的方法,您在此处收到 null。

即使你解决了这个问题,你也会调用 updateComment。您的生产代码不太可能对传入的模拟设置期望,因此您将始终从 commentDto.getCommentText() 收到 null

考虑对 DTO 类使用真实类而不是模拟类。

于 2019-05-08T21:31:29.117 回答