我正在努力让PHPUnit在我的开发环境中工作,但是当我在脚本中包含PHPUnit时,我遇到了一些障碍。我知道我需要在PHP上设置include路径,但是我尝试过的每个组合都会失败,而编译器看不到PHPUnit_Framework_TestCase类。
我刚刚在PHP和PEAR上运行了更新,并且计算机上安装了PHPUnit,因为我可以通过命令行访问它。
PHPUnit安装在 / usr / share / php / PHPunit
Pear位于 / usr / share / php / PEAR
有什么我想念的吗?这是我第一次尝试使用PHPUnit甚至是PEAR的东西。我在Ubuntu 10.10上。任何帮助将不胜感激。
编辑 - 我的PHP ini中的include路径中没有任何内容。现在代码只是
<?php
class Stacktest extends PHPUnit_Framework_TestCase
{
}
我不知道要在include路径中包含什么或设置什么,因为对于网络上有关PHPUnit的所有信息,似乎很少有这些信息。
答案 0 :(得分:26)
从PHPUnit 3.5开始,您必须自己包含自动加载器:
require 'PHPUnit/Autoload.php'; // PEAR should be in your include_path
答案 1 :(得分:16)
如果您正确安装了phpunit(通过PEAR),则不需要包含文件;你只需要改变你用它来测试php文件的方式(例如你用它来测试文件是否通过浏览器类型localhost来工作)。使用phpunit,您可以使用命令行; chapter 5使用命令行给出相同的示例(我认为它是标准的)。因此,如果您正确安装它,您可以这样做:
文件ExampleTest.php,位于localhost的根目录(对我来说这是/ var / www):
class ExampleTest extends PHPUnit_Framework_TestCase
{
public function testOne()
{
$this->assertTrue(FALSE);
}
}
打开控制台(Mac或Linux上的终端,Win上的命令提示符),导航到localhost文档根目录(保存ExampleTest.php的位置)并输入以下内容:
phpunit --verbose ExampleTest.php
您应该看到:
PHPUnit 3.4.13 by Sebastian Bergmann.
F
Time: 1 second, Memory: 6.50Mb
There was 1 failure:
1) ExampleTest::testOne
Failed asserting that <boolean:false> is true.
/var/www/ExampleTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
注意:以上所有内容假设您正确安装了phpunit(如chapter 3中所述)并且之后重新启动了apache。
如果您真的想在浏览器中运行测试,请使用以下代码
# error reporting
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
# include TestRunner
require_once 'PHPUnit/TextUI/TestRunner.php';
# our test class
class ExampleTest extends PHPUnit_Framework_TestCase
{
public function testOne()
{
$this->assertTrue(FALSE);
}
}
# run the test
$suite = new PHPUnit_Framework_TestSuite('ExampleTest');
PHPUnit_TextUI_TestRunner::run($suite);
修改
刚刚在你的问题中发现了Ubuntu 10.10。对于Ubuntu安装,我建议:在终端中执行:
sudo pear uninstall phpunit/PHPUnit
sudo apt-get install phpunit
sudo /etc/init.d/apache2 restart
注意:如果您没有通过pear安装phpunit,请不要发出第一行。似乎需要最后一行(至少在我的情况下)。
sudo /etc/init.d/apache2 reload # Or
sudo service apache2 restart
答案 2 :(得分:6)
将此行添加到php.ini
:
include_path=".:/usr/share/php:/usr/share/pear:/usr/share/php/PHPunit:/usr/share/php/PEAR"
保存文件并重启apache。
另外,请务必编辑正确的php.ini
。尝试使用locate php.ini
查找可能隐藏的所有地点。它通常位于某个地方的/usr
目录下。
答案 3 :(得分:2)
确保每次使用include()或require()时,在实际文件名前加dirname(__FILE__)
。这可以确保您所包含的文件位于您指定的相对于包含的实际文件的路径中。通过deftault,PHP包括相对于调用以启动程序的文件。
答案 4 :(得分:0)
我能够通过在我的脚本顶部使用set_include_path来实现它(参见此处http://www.siteconsortium.com/h/p1.php?id=php002示例),然后我也必须包括,因为我正在运行Selenium测试,但它有效。< / p>
require_once ('PHPUnit/Autoload.php');
require_once 'PHPUnit/Extensions/SeleniumTestCase.php';