gpt4 book ai didi

php - 使用 netbeans 和 PHPUnit 测试 php 函数(不是类)

转载 作者:可可西里 更新时间:2023-11-01 13:23:39 26 4
gpt4 key购买 nike

我想为函数库文件运行单元测试...

也就是说,我没有类,它只是一个带有辅助函数的文件...

例如,我在 ~/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) );
}
?>

工具 -> 创建 PHPUnit 测试给我以下错误:

PHPUnit 3.4.5 by Sebastian Bergmann.

Could not find class "format" in "/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' )
);
}
}
?>

它工作正常,我可以运行它...

但是如果我从 format.php 中选择测试文件,我会得到

Test file for the selected source file was not found

有什么想法吗?

敬礼

SAS

ps:另一个问题,有没有办法更新生成的测试而不需要手动删除它们???

ps2:使用 netbeans 2.8 开发

最佳答案

您编写单元测试用例的方式 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));
}
}

您现在可以像这样使用您的函数,

Format::toProper('something');

PHPUnit 和 Netbeans 都依赖于这种面向对象的哲学。当您尝试自动生成 PHPUnit 测试用例时,PHPUnit 会在您的文件中查找类。然后它基于这个类和它的公共(public) API 创建一个测试用例,并将其称为 ClassNameTest,其中 ClassName 是被测试的类的名称。

Neatbeans 也遵循这个约定,并且知道 ClassNameTestClassName 的 PHPUnit 测试用例,因此在 IDE 中创建了两者之间的链接。

因此,我的建议是尽可能使用类。如果您有不依赖于任何东西且全局使用的实用函数,请将它们设为静态函数。

旁注:我会去掉你的两个函数 toUpper()toLower()。在不需要时,无需包装内置的 PHP 函数。也没有必要对它们进行测试,因为它们已经过全面测试。

站点注释 2:有一种内置的 PHP 等效于您的函数 toProper(),称为 ucfirst()

关于php - 使用 netbeans 和 PHPUnit 测试 php 函数(不是类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1960250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com