Stubbing/Mocking a private method

361 Views Asked by At

I am currently testing a method updateIssuesTable(). this method is a private void method. Even worse, inside this method is a call to getConnection(), which returns a Connection, and is dependent on several private variables, which are dependent on an intialization method, which is of course dependent on something else.

Long story short, this line of code: Connection conn = getConnection();

I don't want to execute at all, I just need a mocked Connection to continue execution. Belowe is the test method:

public void testUpdateIssuesTable() throws Exception {
        PatchWriterTask task = new PatchWriterTask();

        String sql = "update val_issues set PATCH_CREATION_INFO = ? where VAL_ISSUE_ID = ?";
        when(task1.getConnection()).thenReturn(conn);
        when(conn.prepareStatement(sql)).thenReturn(updateStatement);
        Whitebox.invokeMethod(task, "updateIssuesTable");
    }

The method I am testing is as follows:

    private void updateIssuesTable() throws SQLException {

            PreparedStatement createStatement = null;
            String sql = "update val_issues set PATCH_CREATION_INFO = ? where VAL_ISSUE_ID = ?";
            Connection conn = getConnection();
            createStatement = conn.prepareStatement(sql);
            ...
    }

EDIT: I create a mocked Connection in my test class:

private Connection conn = mock(Connection.class);
1

There are 1 best solutions below

0
On

You should get connection from a connection pool (C3P0 or Tomcat Connection Pool are good candidates), then you can mock the ConnectionPool.getConnection() method to return a connection mock.

Other than that look for @RunWith MockitoJUnitRunner examples to show how you can @InjectMocks into your test classes. No shortcuts here - its easy enough when you know how but will take a bit of time to master.