Mocking static methods with Mockito

后端 未结 15 1089
Happy的楠姐
Happy的楠姐 2020-11-21 06:51

I\'ve written a factory to produce java.sql.Connection objects:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory         


        
15条回答
  •  [愿得一人]
    2020-11-21 07:37

    You can do it with a little bit of refactoring:

    public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {
    
        @Override public Connection getConnection() {
            try {
                return _getConnection(...some params...);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    
        //method to forward parameters, enabling mocking, extension, etc
        Connection _getConnection(...some params...) throws SQLException {
            return DriverManager.getConnection(...some params...);
        }
    }
    

    Then you can extend your class MySQLDatabaseConnectionFactory to return a mocked connection, do assertions on the parameters, etc.

    The extended class can reside within the test case, if it's located in the same package (which I encourage you to do)

    public class MockedConnectionFactory extends MySQLDatabaseConnectionFactory {
    
        Connection _getConnection(...some params...) throws SQLException {
            if (some param != something) throw new InvalidParameterException();
    
            //consider mocking some methods with when(yourMock.something()).thenReturn(value)
            return Mockito.mock(Connection.class);
        }
    }
    

提交回复
热议问题