模拟 JDBC 的连接 #prepareStatement 总是使用 jMockit 返回空值



我正在尝试用jMockit测试JDBC对OracleDB的调用。我曾尝试模拟JDBC的Connection#prepareStatement(String sql)来返回PreparedStatement模拟对象,但我只得到了一个null值。我的目标是模拟Connection API以返回一个模拟PreparedStatement对象,并模拟PreparetStatement API以返回模拟ResultSet对象。

我的源代码如下。

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;

当我调用时

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

我的单元测试如下

@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.

我使用的是最新版本的jMockit发布的TestNG 6.10。我正在使用TestNG eclipse插件运行单元测试。我将-javaagent:C:downloadsjmockit.jar作为Eclipse中的VM参数传递。

更新:该方法接受jMockit提供的两个模拟参数。如果我不传递java代理,那么TestNG会抛出一个错误,期望参数通过TestNG的dataProvider功能传递。http://testng.org/doc/documentation-main.html#parameters-数据提供商

它确实返回了一个mock对象,但它采用默认行为。例如,我想捕获传递给ps.setString(1, empId)的值,或者模拟rs.next()以返回true。但只返回默认输出。

这不是一个bug。这是一个功能:)

您需要配置mock。默认情况下,它们将返回null。

您需要添加"期望值"-s,如上所示http://jmockit.org/tutorial/Mocking.html

最新更新