当我模拟一个链式方法调用时,我会得到一个null指针异常。
我的代码是这样的:
@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));
如果这不是你想要的,看看这个例子。根据这一点,返回深层存根应该可以解决问题。
尝试使用Mockito注释模拟Comment对象:
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
Comment youtubeCommentOne;