How mock internal method call with EasyMock and PowerMock?

I have JDBC connection class as below. Need to mock the Connection class with Easy Mock and Power Mock. It is throwing below error.I’m new to unit testing. Please give some suggestion to fix this issue. If I remove the connection.isClosed() method test is passing.

public class ConnectionFactory {

    private static volatile Connection connection        = null;
    private ConnectionFactory() {
    }

    public static Connection getConnection() {   
        try {

            if (connection == null || connection.isClosed()) {

                try {     
                            Class.forName(DB_DRIVER);
                            connection = DriverManager.getConnection(DB_CONNECTION_URL, DB_USER, DB_PASSWORD);

                        ...

I have mock the connection as below.

@RunWith(PowerMockRunner.class)
public class ConnectionFactoryTest {

    @Test
    public void testGetConnection() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {

        Connection mockConnection = PowerMock.createMock(Connection.class);
        PowerMock.replayAll();
        Field connectionField = ConnectionFactory.class.getDeclaredField("connection");
        connectionField.setAccessible(true);
        connectionField.set(null, mockConnection);

        assertNotNull(ConnectionFactory.getConnection());

    }

}

Error

java.lang.AssertionError: 
  Unexpected method call Connection.isClosed():
    at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
    at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)


Source: java

Leave a Reply