Mock DriverManager.getconnection method for junit/mockito unit tests

79 Views Asked by At

How can i mock the DriverManager.getconnection method. I am new to junit and mockito and learning the use of the same. Any suggestion would be highly appreciated. Thanks in advance.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.my.config.project.dsexecutor.model.DSConfig;

public class dsexecutor {
    public JsonArray readTableDataAsJson(String sqlQuery, DSConfig dataConfig) throws SQLException {

        String host = dataConfig.getHost();
        String httpPath = dataConfig.getHttpPath();
        String accessToken = dataConfig.getAccessToken();
        String username = dataConfig.getUsername();
   
        String jdbcString = String.format(
                "jdbc:datatest://%s:443;EnableArrow=0;transportMode=http;ssl=1;httpPath=%s;AuthMech=3;UID=token;PWD=%s",
                host, httpPath, accessToken);

        try (Connection conn = DriverManager.getConnection(jdbcString, username, accessToken);
                Statement stmt = conn.createStatement()) {
            try (ResultSet resultSet = stmt.executeQuery(sqlQuery)) {
                JsonArray jsonArray = new JsonArray();
                while (resultSet.next()) {
                    JsonObject jsonObject = new JsonObject();
                    ResultSetMetaData metaData = resultSet.getMetaData();
                    int numColumns = metaData.getColumnCount();
                    for (int i = 1; i <= numColumns; i++) {
                        String columnName = metaData.getColumnName(i);
                        String columnValue = resultSet.getString(i);
                        jsonObject.addProperty(columnName, columnValue);
                    }
                    jsonArray.add(jsonObject);
                }
                return jsonArray;
            }
        }
    }
}
1

There are 1 best solutions below

0
tgdavies On

Create a class to wrap the static call.

public class ConnectionProvider {
  private final String jdbcString;
  ...
  public Connection getConnection() {
     return DriverManager.getConnection(jdbcString, username, accessToken);
  }
}

Then mock this class.