【问题标题】:Writing PHPUnit test for a class which extends another class produces a 'Class not found' error为扩展另一个类的类编写 PHPUnit 测试会产生“找不到类”错误
【发布时间】:2019-10-28 11:45:47
【问题描述】:

我有什么:

  1. WPKit/Module/AbstractFunctions.php抽象类;
  2. wp-content/themes/mytheme/modules/quiz/Functions.php:
    use WPKit\Module\AbstractFunctions;
    class Functions extends AbstractFunctions { ... }
    
  3. wp-content/themes/mytheme/tests/quiz/QuizFunctionsTest.php:

    require_once dirname(__FILE__) . "/../../modules/quiz/Functions.php";
    
    class QuizFunctionsTest extends TestCase {
        public function testGetQuizByID() {
            # some code
        }
    }
    

运行phpunit QuizFunctionsTest.php时,出现以下错误:

PHP Fatal error: Class '%path%\AbstractFunctions' not found in %path%/modules/quiz/Functions.php on line 18

我尝试了require_once 缺失的课程,但没有帮助。在测试类之外,我的代码工作得很好。有什么想法吗?

【问题讨论】:

  • 您能否提供更多信息 - 1. 您如何运行它? 2.如何在这个.../modules/quiz/Functions.php里面导入AbstractFunctions
  • @AlexMozharov 我已经扩展了应该回答您问题的问题
  • 谢谢,我现在看到您使用命名空间。我认为这可能会有所帮助stackoverflow.com/questions/15719293/…
  • 您也可以在stackoverflow.com/q/25219764/576767 找到一些帮助,但实际上很难说,这取决于您使用的自动加载系统以及您的 phpunit 套件的配置。通常你会为 phpunit 指定一个引导文件,其中包括 vendor/autoload.php
  • 似乎我无法让它工作,因为它是一个 WordPress 设置所以我所做的是通过 wget 安装 PHPUnit 并使用 WP-CLI 来搭建主题测试,然后它就像一个魅力.

标签: php oop testing phpunit fatal-error


【解决方案1】:

TL;DR:我似乎无法让它工作,因为它是一个 WordPress 设置,所以我所做的是通过 wget 安装 PHPUnit 并使用 WP-CLI 来搭建主题测试,然后它像魅力一样工作。


首先我在我的主题目录中从终端安装了 PHPUnit:

wget -O phpunit https://phar.phpunit.de/phpunit-7.phar
chmod +x phpunit

接下来我安装了 WP-CLI:

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

接下来设置测试套件:

wp scaffold theme-tests your-theme-slug

还要确保您已安装 svn

就我而言(我也发现有人提到它)我不得不删除 /tmp/wordpress/tmp/wordpress-tests-lib 并重新运行之前的命令两次,因为脚本不知何故没有下载所有内容。

请注意,您将在 /tmp/wordpress 中设置单独的 WordPress。在我的主要 WordPress 设置中,我使用 WPKit 库,该库存储在 wp-content 附近的 WordPress 根目录中,因此我必须将其复制到 /tmp/wordpress,否则我的 PHPUnit 测试找不到包含在我必须测试的类中的 WPKit 文件.

所以当您运行wp scaffold 时,它会在您的主题根目录中创建bin 目录。从主题根目录运行以下命令以安装测试套件:

bin/install-wp-tests.sh <test-database-name> <user> <password> <host> <wordpress-version>

就我而言,它看起来像:

bin/install-wp-tests.sh wp_test root '' localhost latest

请务必使用 empty 数据库,因为每次运行 PHPUnit 都会清除数据库,因此您可能会丢失数据。

在完成所有这些操作之后,只需运行 PHPUnit 就可以了:

./phpunit

它在your-theme/tests 目录中运行测试。默认情况下,它会忽略默认测试文件,因此请使用它来进行自己的简单测试以检查一切是否正常。

哇哦。


来源:


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2013-12-23
    • 2018-07-10
    • 2017-06-08
    • 2017-03-14
    • 2013-09-23
    • 2018-06-05
    相关资源
    最近更新 更多