【问题标题】:Why is PHPUnit still failing on SQL error, even though I have caught the exception为什么 PHPUnit 在 SQL 错误上仍然失败,即使我已经捕获了异常
【发布时间】:2015-05-15 15:55:32
【问题描述】:

我正在尝试构建一个包装类,以简化我的应用程序中的 SQL 访问(除其他外)。在使用 PHPUnit 测试我的类时,尽管我已经捕获并处理了异常,但 SQL 错误会终止测试并将错误消息吐出到控制台。

我尝试过使用@expectedexception。这行得通,除了我现在不能再做任何断言了;我想测试该方法是否将错误作为数组返回。

非常感谢任何帮助。

$db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

// Prepare query and respond to errors. If there is errors, stop processing any more queries
try {
    $PDOQuery = $db->prepare($query['query']);
}
catch ( PDOException $error )
{
    $error = $error->errorInfo;
    $this->parent->errors[] = array( 'type' => 'Database error (Prepare)',
        'details' => 'The MySQL server returned an error. Check your DB logs for more details' );

    error_log( "SQL Prepare Error code (SQLSTATE): $error[0]");
    error_log( "SQL Prepare Error code (Vendor): $error[1]");
    error_log( "SQL Prepare Error message: $error[2]");
    break;
}


try {
    // Execute query and respond to errors. If there is errors, stop processing any more queries
    $result = $PDOQuery->execute(isset ($query['params']) ? $query['params'] : array());
}

catch ( PDOException $error ) {
    $error = $error->errorInfo();

    $logsMessage = "Check your server logs for more information.";

    switch($error[1])
    {
        case 1452: $message = "MySQL failed to add a row. Possibly you missed out some mandatory fields? $logsMessage"; break;
        default: $message = "MySQL Returned an error (Execute). $logsMessage"; break;
    }

    $this->parent->errors[] = array( 'type' => 'Database error',
        'details' => $message );

    error_log( "SQL Execute Error code (SQLSTATE): $error[0]");
    error_log( "SQL Execute Error code (Vendor): $error[1]");
    error_log( "SQL Execute Error message: $error[2]");
    break;
}

【问题讨论】:

    标签: php database phpunit


    【解决方案1】:

    好的,所以我找出了问题所在。

    我的代码位于命名空间中,但我忘记在 catch 语句中引用全局命名空间。

    所以我改成

    catch ( \PDOException $error )

    我的问题自己解决了。

    【讨论】:

      猜你喜欢
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 2023-01-10
      • 2020-12-10
      • 1970-01-01
      相关资源
      最近更新 更多