最终 class 中的 Powermock 链式方法调用

Powermock chained method calls in final class

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

我的代码是这样的:

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

}

我做错了什么?

拆分链式方法调用应该可行:

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;