【问题标题】:Using PHPUnit to test WordPress functions ($wpdb)使用 PHPUnit 测试 WordPress 函数 ($wpdb)
【发布时间】:2013-08-02 23:58:24
【问题描述】:

我正在编写一个 WordPress 主题。有一些后端类通过 $wpdb 变量(“sql-connector.php”)与 SQL 数据库对话。在 WordPress 主题中,某些页面会包含这个 php 页面并创建一个 db_connector 对象,我可以在其中立即使用 global $wpdb

sql-connector.php:

<?php

class db_connector {

function verify_account($em, $pwd) {
    global $wpdb; 

    echo "em = ". $em;
    echo "pwd = ". $pwd; 

    $query = 
        "
        SELECT id
        FROM data_customers
        WHERE email = %s AND password = %s
        ";

    /* customer_id */               
    $result = $wpdb->get_var($wpdb->prepare($query, $em, $pwd));

    echo "empty? = ".!empty($result);

    return $result;
}

}?>

现在我想用 PHPUnit 来测试函数verify_account($em, $pwd)。我使用下面的代码。

sql-connectorTest.php:

<?php

include("sql-connector.php");

class db_connectorTest extends PHPUnit_Framework_TestCase{
    private $db_connector;

    function testVerify_account() {
        $db_connector = new db_connector();

        $result = $db_connector->verify_account("username@email.com", md5("password"));

        $this->assertEmpty($result);
    }


}

?>

运行 PHPUnit,它只会给出以下结果:

MacBruce:model bruce$ phpunit sql-connectorTest.php
PHPUnit 3.7.22 by Sebastian Bergmann.

em = username@email.compwd = 5f4dcc3b5aa765d61d8327deb882cf99MacBruce:model bruce$ 

它似乎在想使用$wpdb-&gt;get_var(...) 函数时卡住了。 $wpdb 好像是空的。

我对 PHPUnit 和 WordPress 非常陌生。我错过了包含任何 WordPress/PHPUnit 库吗?还是我错过了包含一些我自己的 php 文件?

谢谢。

【问题讨论】:

    标签: unit-testing phpunit wordpress


    【解决方案1】:

    您需要一个与数据库 ($wpdb) 的活动连接,并使用所有凭据进行实例化, 然后在你的测试中使用它。尽量避免使用全局变量,在构造函数或 setter 中传递。

    另外,您可能想看看一些现成的 wordpress 测试工具,例如 http://wptest.io/

    【讨论】:

      【解决方案2】:

      我刚刚设置了 PHPUnit 和 WP。诀窍是它需要自己安装 WordPress 源文件和自己的数据库实例,然后可以设置和拆除测试环境。

      我使用了这些指南:

      一个警告是 PHPUnit can serialise $wpdb unless you tell it not to,这也会破坏你的数据库连接。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-22
        • 1970-01-01
        • 1970-01-01
        • 2016-12-19
        • 2017-09-21
        • 2014-09-06
        • 2014-02-10
        • 2020-05-23
        相关资源
        最近更新 更多