PHPUnit不会自动检测目录中的文件



所以我试图在WordPress中创建一些单元测试,并安装了PHPUnit 6.5.5(尝试了各种版本,最高可达7.*,这是WP支持的最新版本(。

生成的phpunit.xml.dist文件如下所示:

<?xml version="1.0"?>
<phpunit
bootstrap="tests/bootstrap.php"
backupGlobals="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
>
<testsuites>
<testsuite name="default">
<directory prefix="test-" suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>

tests文件夹是默认文件夹,包含bootstrap.php和test-sample.php文件:

tests
-- bootstrap.php
-- test-sample.php

但是,当我在插件的目录中并运行phpunit时,我会得到没有执行任何测试

当我在目录下添加测试文件时:

<file>tests/test-sample.php</file>

然后运行phpunit,我可以看到测试正在运行。

难道它不应该自动检测测试套件中的目录和文件,而不需要在XML中逐个写入每个测试文件吗?

编辑:phpunit -v输出:

$ phpunit -v
Installing...
Running as single site... To run multisite, use -c tests/phpunit/multisite.xml
Not running ajax tests. To execute these, use --group ajax.
Not running ms-files tests. To execute these, use --group ms-files.
Not running external-http tests. To execute these, use --group external-http.
PHPUnit 6.5.5 by Sebastian Bergmann and contributors.
Runtime:       PHP 7.3.14-1+ubuntu18.04.1+deb.sury.org+1
Configuration: /vagrant/Plugins/Framework/phpunit.xml.dist

Time: 1 second, Memory: 26.00MB

编辑2:bootstrap.php文件内容:

<?php
/**
* PHPUnit bootstrap file
*/
$_tests_dir = getenv( 'WP_TESTS_DIR' );
if ( ! $_tests_dir ) {
$_tests_dir = rtrim( sys_get_temp_dir(), '/\' ) . '/wordpress-tests-lib';
}
if ( ! file_exists( $_tests_dir . '/includes/functions.php' ) ) {
echo "Could not find $_tests_dir/includes/functions.php, have you run bin/install-wp-tests.sh ?" . PHP_EOL; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
exit( 1 );
}
// Give access to tests_add_filter() function.
require_once $_tests_dir . '/includes/functions.php';
/**
* Manually load the plugin being tested.
*/
function _manually_load_plugin() {
require realpath(dirname(__FILE__) . '/../..') . '/myplugin/myplugin.php';
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );
// Start up the WP testing environment.
require $_tests_dir . '/includes/bootstrap.php';
  • 没有命令行选项的phpunit

当您在没有命令行选项的情况下运行phpunit时,您应该想知道当前的工作目录是什么,正如您在phpunit 6.5文档中看到的那样。如果当前工作目录中存在phpunit.xml或phpunit.xml.dist(按顺序(,并且未使用--configuration,则会自动从该文件中读取配置。

  • 带有命令行选项的phpunit

如果你想从一个不包含phpunit.xml的目录(例如你的插件目录(运行phpunit,你必须通过正确的路径:

phpunit --configuration /vagrant/Plugins/Framework/phpunit.xml.dist

当您在phpunit.xml.dist中配置bootstrap="tests/bootstrap.php"时,phpunit将在/vagrant/Plugins/Framework/tests目录中查找bootstrap.php文件。

您的bootstrap.php文件包含以下行:

$_tests_dir = getenv( 'WP_TESTS_DIR' ); if ( !$_tests_dir ) $_tests_dir = '/tmp/wordpress-tests-lib';

我建议您将其替换为:$_tests_dir = '/tmp/wordpress-tests-lib';

您也可以将其添加到~/.bash_profile中,以避免重复替换:

export WP_TESTS_DIR='/tmp/wordpress-tests-lib'

最新更新