简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM