RITZ XAVI
RITZ XAVI

Reputation: 3789

How to unit test chained method call(s) using Mockito

I am working on a J2EE project which uses the JIRA's REST Client. This client returns a Jira issue object. Some of the fields of the Issue class are key, self, id, summary, etc etc. The self field here is basically a URI.
For Eg http://jira.company.com/rest/api/2.0/issue/12345 I have a use case where I have to retrieve the host from the URI specified above.

I can do that by something like issue.getSelf().getHost().
issue.getSelf() returns an object of type 'URI' and to get the host I can simply use the getHost() method provided by the URI class which returns the host url in String format.

Everything works fine. I am facing problem in unit testing this piece of code using Mockito. I don't know how to mock chained method calls.

I have the following code snippet.

private static final String JIRA_HOST = "jira.company.com";
@Mock private com.atlassian.jira.rest.client.api.domain.Issue mockIssue;

@Before
    public void setup() {
        when(mockIssue.getSelf().getHost()).thenReturn(JIRA_HOST);
    }

Here, I get a Null Pointer Exception.

After doing much research, I came to know that I will have to use @Mock(answer = Answers.RETURNS_DEEP_STUBS) private com.atlassian.jira.rest.client.api.domain.Issue mockIssue;.
But this also gives me a Null Pointer Exception.

Can someone tell me how can I mock chained method calls.

Upvotes: 6

Views: 11716

Answers (1)

nickb
nickb

Reputation: 59699

You don't need RETURNS_DEEP_STUBS or whatever that mock annotation is. You just have to mock every object that you want to return in the chain, similar to this:

@Mock Issue issue;
@Mock URI uri;

@Before
public void setup() {
    when(uri.getHost()).thenReturn(JIRA_HOST);
    when(issue.getSelf()).thenReturn(uri);
}

Upvotes: 10

Related Questions