vendredi 29 avril 2016

Mocking JDBC's Connection#prepareStatement always returns null with jMockit

I am trying to test JDBC calls to Oracle DB with jMockit. I have tried to simulate JDBC's Connection#prepareStatement(String sql) to return PreparedStatement mock object, but I only get a null value instead. My aim is to mock Connection APIs to return a mock PreparedStatement object, and to mock PreparedStatement APIs to return a mock ResultSet object. Any advice would be gratefully appreciated.

My source code is given below.

try (Connection conn = DriverManager.getConnection(url, username, password);) {
  try(PreparedStatement ps = conn.prepareStatement(
         "SELECT firstName, lastName from Employee where empId = ?");) {
    ps.setString(1, empId); // This is an input to function.
    try(ResultSet rs = ps.executeQuery();) {
      while(rs.next()) {
        Employee emp = new Employee();
        emp.setFirstName(rs.getString("firstName"));
        emp.setLastName(rs.getString("lastName"));
        return emp;
      }
    }
  }
}
return employees;

When I invoke

PreparedStatement ps = conn.prepareStatement(
             "SELECT firstName, lastName from Employee where empId = ?")

My unit test is as follows

@Test()
  public void testQueryOutOfDateSpanishContent_Success(
      @Mocked final Connection connection, @Mocked final PreparedStatement ps) throws Exception {
    new Expectations(DriverManager.class) {
      {
        DriverManager.getConnection(
            dcrParameters.getEnvironmentUrl(), dcrParameters.getUsername(),
            dcrParameters.getPassword());
        result = connection;

        connection.prepareStatement(anyString);
        result = with(new Delegate<PreparedStatement>() {
          public PreparedStatement prepareStatement(String sql) throws SQLException {
            return ps;
          }
        });
      }
    };
    // Call the source function here.

I am using TestNG 6.10 with latest version of jMockit release. I am running the unit test with TestNG eclipse plugin. I am passing -javaagent:C:\downloads\jmockit.jaras a VM argument in Eclipse.

Thanks!!

Aucun commentaire:

Enregistrer un commentaire