Powermock链式方法调用最终类

时间:2016-05-12 15:38:56

标签: java mockito powermock

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

我的代码看起来像这样:

@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);

}

我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

拆分链式方法调用应该有效:

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;