我将phpunit安装为PHar:
- 从 wget http://pear.phpunit.de/get/phpunit.phar 下载了 PHar 文件
- 将其保存在 (/usr/share/phpunit) 中。
- 使其可执行(
chmod +x phpunit.phar
)。 - 在/usr/bin 中创建了一个指向它的链接。
现在我可以调用它了,但我必须在 require 调用中定义测试类的路径,要么从目录中调用 relativ,我从目录中调用 phpunit(示例 1),要么绝对从根(示例 2)。
示例 1 (文件/var/www/sandbox/phpunit/tests/FooTest.php)
<?php
require_once('../Foo.php');
class FooTest extends PHPUnit_Framework_TestCase {
public function testBar() {
$input = 5;
$this->assertEquals(5, (new Foo())->bar());
}
}
示例 2(文件/var/www/sandbox/phpunit/tests/FooTest.php)
<?php
require_once('/var/www/sandbox/phpunit/Foo.php');
class FooTest extends PHPUnit_Framework_TestCase {
public function testBar() {
$input = 5;
$this->assertEquals(5, (new Foo())->bar());
}
}
我需要配置什么(以及如何配置)才能使用基于主机根目录的路径? 例如,如果/var/www/sandbox/phpunit/是我网站的根文件夹:
<?php
require_once('/Foo.php');
class FooTest extends PHPUnit_Framework_TestCase {
public function testBar() {
$input = 5;
$this->assertEquals(5, (new Foo())->bar(5));
}
}
感谢
好吧,如果您不通过网络运行程序,您将无法引用 Web 根目录。这一点是相当明显的。
我能想到的最佳解决方案是将 Web 根硬编码为 phpunit 配置或引导程序中的变量或常量,或者使用魔术常量__DIR__
引用相对于当前文件的文件。
无论如何,即使我通过 Web 加载,我也倾向于使用后者,因为它允许我的代码从子目录托管,而不必担心 Web 根目录在哪里。
感谢您的回复!
我已经用Arne Blankerts的Autoload/phpab重新定义了它。它调用 spl_autoload_register
函数,并将闭包作为第一个参数,并在此匿名函数中定义类名及其文件的生成数组(具有 'myclass' => '/path/to/MyClass.php'等元素)。我已经将生成的文件包含在我的phpunit引导程序.php中。现在它正在工作。:)
# phpab -o autoload.inc.php .
我的文件结构:
/qwer
/qwer/Foo.php
/tets
/tets/FooTest.php
/tets/phpunit.xml
/autoload.inc.php
/bootstrap.php
/qwer/Foo.php
<?php
class Foo {
public function bar($input) {
return $input;
}
}
/tets/FooTest.php
<?php
class FooTest extends PHPUnit_Framework_TestCase {
public function testBar() {
$input = 5;
$this->assertEquals(5, (new Foo())->bar(5));
}
}
/tets/phpunit.xml
<phpunit bootstrap="../bootstrap.php" colors="true">
</phpunit>
/autoload.inc.php
<?php
// @codingStandardsIgnoreFile
// @codeCoverageIgnoreStart
// this is an autogenerated file - do not edit
spl_autoload_register(
function($class) {
static $classes = null;
if ($classes === null) {
$classes = array(
'foo' => '/qwer/Foo.php',
'footest' => '/tests/FooTest.php'
);
}
$cn = strtolower($class);
if (isset($classes[$cn])) {
require __DIR__ . $classes[$cn];
}
}
);
// @codeCoverageIgnoreEnd
/引导程序.php
<?php
require_once 'autoload.inc.php';
编辑:
这种方法的一个缺点是,每次创建新类后我都必须启动 phpab。 好的,对于小型测试项目,可以使用两个突击队的组合:
# phpab -o ../autoload.inc.php .. && phpunit .
或者与别名相同,例如 myprojectphpunit
.