LupoZ
LupoZ

Reputation: 201

Powermock chained method calls in final class

when I mock a chained method call I get a nullpointer exception.

My code is looking like this:

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

}

What am I doing wrong here?

Upvotes: 1

Views: 1349

Answers (1)

AniaG
AniaG

Reputation: 254

Splitting a chain method call should work:

Comment commentMock = PowerMockito.mock(Comment.class);
CommentThread commentThreadMock = PowerMockito.mock(CommentThread.class);

when(commentMock.getSnippet()).thenReturn(commentThreadMock);
when(commentThreadMock.getUpdatedAt()).thenReturn(new DateTime(youtubeCommentOneDate));

If it's not what you are looking for, check out this example. According to this, returning deep stubs should solve the problem.

Try to mock Comment object using Mockito annotation:

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

Upvotes: 3

Related Questions