我有一个PHP项目,项目结构如下。
php_test_app
src
Vegetable.php
tests
StackTest.php
VegetableTest.php
这些文件的代码如下所示。我在Eclipse中使用PDT和PTI。Eclipse中的PHPUnit识别出VegetableTest.php
属于Vegetable.php
,因为您可以使用切换按钮在它们之间切换。
我首先尝试通过在PHP资源管理器中选择tests目录并单击Run Selected PHPUnit Test
来运行测试代码。它运行两个测试,两个VegetableTest
都失败,并出现以下跟踪:Fatal error: Class 'Vegetable' not found in /Users/erwin/Documents/workspace/php_test_app/tests/VegetableTest.php on line 8
。这里发布了一个类似的问题:phpunit找不到Class,PHP致命错误。
事实上,我还没有包含我的源代码,所以现在我取消了VegetableTest.php
中包含的注释,如下所示。如果我现在尝试以同样的方式运行测试,PHPUnit将无法识别任何测试代码!即使是未改变的StackTest
也不被识别。
- 我应该如何使include使得单元测试是否被认可
- 我需要指定完整路径,还是只指定的名称定义类的文件
更改include语句也不起作用;我试过以下几种。
include 'Vegetable.php';
include 'src/Vegetable.php';
include '../src/Vegetable.php';
Vegetable.php
<?php
// base class with member properties and methods
class Vegetable {
var $edible;
var $color;
function Vegetable($edible, $color="green")
{
$this->edible = $edible;
$this->color = $color;
}
function is_edible()
{
return $this->edible;
}
function what_color()
{
return $this->color;
}
} // end of class Vegetable
// extends the base class
class Spinach extends Vegetable {
var $cooked = false;
function Spinach()
{
$this->Vegetable(true, "green");
}
function cook_it()
{
$this->cooked = true;
}
function is_cooked()
{
return $this->cooked;
}
} // end of class Spinach
StackTest.php
<?php
class StackTest extends PHPUnit_Framework_TestCase
{
public function testPushAndPop()
{
$stack = array();
$this->assertEquals(0, count($stack));
array_push($stack, 'foo');
$this->assertEquals('foo', $stack[count($stack)-1]);
$this->assertEquals(1, count($stack));
$this->assertEquals('foo', array_pop($stack));
$this->assertEquals(0, count($stack));
}
}
?>
VegetableTest.php
<?php
// require_once ('../src/Vegetable.php');
class VegetableTest extends PHPUnit_Framework_TestCase
{
public function test_constructor_two_arguments()
{
$tomato = new Vegetable($edible=True, $color="red");
$r = $tomato.is_edible();
$this->assertTrue($r);
$r = $tomato.what_color();
$e = "red";
$this->assertEqual($r, $e);
}
}
class SpinachTest extends PHPUnit_Framework_TestCase
{
public function test_constructor_two_arguments()
{
$spinach = new Spinach($edible=True);
$r = $spinach.is_edible();
$this->assertTrue($r);
$r = $spinach.what_color();
$e = "green";
$this->assertEqual($r, $e);
}
}
?>
phpunit --bootstrap src/Vegetable.php tests
指示PHPUnit在运行tests
中的测试之前加载src/Vegetable.php
。
请注意,--bootstrap
应该与自动加载器脚本一起使用,例如Composer或PHPAB生成的脚本。
还可以查看PHPUnit网站上的"入门"部分。