我安装了phpunit作为PHAR:
chmod +x phpunit.phar
)。现在我可以调用它,但是我必须在require调用中定义测试类的路径,或者从目录中调用相对而来,我从(s。例1)调用phpunit,或者绝对从root(s)调用例子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));
}
}
THX
答案 0 :(得分:1)
如果您没有通过网络运行该程序,则无法引用Web根目录。这很明显。
我能想到的最佳解决方案是将web根硬编码为phpunit config或bootstrap文件中的变量或常量,或者使用魔术常量__DIR__
来引用相对于当前文件的文件文件。
我倾向于使用后者,即使我通过网络加载,因为它允许我的代码从子目录托管,而不必担心Web根目录的位置。
答案 1 :(得分:0)
感谢您的回复!
我已经用Arne Blankerts'Autoload / phpab重新获得了它。它使用闭包作为第一个参数调用spl_autoload_register
函数,并在此匿名函数中定义类名及其文件的生成数组(使用'myclass'=&gt;'/ path / to / MyClass.php'等元素)。我已将生成的文件包含到我的phpunit bootstrap.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
/bootstrap.php
<?php
require_once 'autoload.inc.php';
编辑:
这种方法的一个缺点是,每次创建新类后我都必须启动phpab。好的,对于小型测试项目,可以使用两个突击队的组合:
# phpab -o ../autoload.inc.php .. && phpunit .
或者与myprojectphpunit
等别名相同。