【问题标题】:Powermock chained method calls in final class最终类中的Powermock链式方法调用
【发布时间】:2016-05-12 15:38:56
【问题描述】:

当我模拟一个链式方法调用时,我得到一个空指针异常。

我的代码如下所示:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Comment.class, CommentThread.class})
public class YoutubeTest {

@Test
public void testSortCommentsByDate() {
Comment youtubeCommentOne = PowerMockito.mock(Comment.class); // This is a final class

Mockito.when(youtubeCommentOne.getSnippet().getUpdatedAt().getValue()).thenReturn(youtubeCommentOneDate);

}

我在这里做错了什么?

【问题讨论】:

    标签: java mockito powermock


    【解决方案1】:

    拆分链方法调用应该可以:

    Comment commentMock = PowerMockito.mock(Comment.class);
    CommentThread commentThreadMock = PowerMockito.mock(CommentThread.class);
    
    when(commentMock.getSnippet()).thenReturn(commentThreadMock);
    when(commentThreadMock.getUpdatedAt()).thenReturn(new DateTime(youtubeCommentOneDate));
    

    如果不是您要查找的内容,请查看 this 示例。 据此,返回深存根应该可以解决问题。

    尝试使用 Mockito 注释来模拟 Comment 对象:

    @Mock(answer = Answers.RETURNS_DEEP_STUBS) 
    Comment youtubeCommentOne;
    

    【讨论】:

    • 感谢您的帮助。这正是我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    相关资源
    最近更新 更多