Mock nested method calls using Mockito in Spring Boot

Quite often you have a nested call chain to get a result in Java. Mocking these in a test is a little different than mocking just one call. I’m here going to show a solution to that.

Say you have the following call chain to create a transacted session for a JMS connection:

Session session = 
           connectionFactory.createConnection()
                            .createSession(Session.SESSION_TRANSACTED);

To mock these calls we have to break them apart and mock them one by one

    
...
public MyTestClass {
  @Mock
  private Session session;

  @Mock
  private ConnectionFactory connectionFactory;

  @Mock
  private Connection mockedConnection;

  @BeforeMethod
  public void setUp() throws JMSException {
    MockitoAnnotations.initMocks(this);
    Mockito.when(connectionFactory.createConnection())
                                          .thenReturn(mockedConnection);
    Mockito.when(mockedConnection.createSession(
                                           Session.SESSION_TRANSACTED))
                                          .thenReturn(session);
  }
...

We are now ready to create all our tests 🙂

Tested on Java v1.8.0_252, Mockito v3.3.3, Spring Boot v2.2.4 and TestNG v6.11

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.