ope*_*sas 6 php phpunit unit-testing netbeans
我想为函数库文件运行单元测试...
也就是说,我没有一个类,它只是一个带有辅助函数的文件...
例如,我在〜/ www/test创建了一个php项目
和一个文件〜/ www/test/lib/format.php
<?php
function toUpper( $text ) {
return strtoupper( $text );
}
function toLower( $text ) {
return strtolower( $text );
}
function toProper( $text ) {
return toUpper( substr( $text, 0, 1 ) ) . toLower( substr( $text, 1) );
}
?>
Run Code Online (Sandbox Code Playgroud)
工具 - >创建PHPUnit测试给出了以下错误:
Sebastian Bergmann的PHPUnit 3.4.5.
在"/home/sas/www/test/lib/format.php"中找不到类"格式".
现在,如果我编码(手工!)文件〜/ www/test/tests/lib/FormatTest.php
<?php
require_once 'PHPUnit/Framework.php';
require_once dirname(__FILE__).'/../../lib/format.php';
class FormatTest extends PHPUnit_Framework_TestCase {
protected function setUp() {}
protected function tearDown() {}
public function testToProper() {
$this->assertEquals(
'Sebastian',
toProper( 'sebastian' )
);
}
}
?>
Run Code Online (Sandbox Code Playgroud)
它工作正常,我可以运行它...
但如果我从format.php中选择测试文件,我会得到
找不到所选源文件的测试文件
任何的想法?
saludos
SAS
ps:另一个问题,有没有办法更新生成的测试而不必手动删除它们?
ps2:使用netbeans 2.8 dev
你如何编写单元测试用例是100%正确的.问题在于常见的约定以及PHPUnit和Netbeans如何依赖它们.
这些天的最佳实践是以面向对象的方式编写所有代码.因此,不像拥有像你一样的实用函数的PHP文件,而是将这些函数包装到一个类中,并将它们作为静态函数.以下是使用上述代码的示例,
<?php
class Format
{
public static function toUpper($text)
{
return strtoupper($text);
}
public static function toLower($text)
{
return strtolower($text);
}
public static function toProper($text)
{
return self::toUpper(substr($text, 0, 1 )) . self::toLower(substr($text, 1));
}
}
Run Code Online (Sandbox Code Playgroud)
你现在使用你的功能,
Format::toProper('something');
Run Code Online (Sandbox Code Playgroud)
PHPUnit和Netbeans依赖于这种面向对象的哲学.当您尝试自动生成PHPUnit测试用例时,PHPUnit会在您的文件中查找类.然后它根据这个类和它的公共API创建一个测试用例,并调用它ClassNameTest
,其中ClassName
是被测试类的名称.
Neatbeans也遵循这个约定并且知道这ClassNameTest
是一个PHPUnit测试用例ClassName
,因此在IDE中创建两者之间的链接.
所以,我的建议是尽可能地使用课程.如果您具有不依赖于任何东西并且全局使用的实用程序函数,请将它们设置为静态函数.
附注:我会干掉你的两个函数toUpper()
和toLower()
.当没有必要时,不需要包含内置的PHP函数.由于经过全面测试,因此无需对其进行测试.
网站注释2:有一种内置的PHP相当于你的函数toProper()
叫ucfirst()
.