【问题标题】:test php functions (not classes) with netbeans and PHPUnit使用 netbeans 和 PHPUnit 测试 php 函数(不是类)
【发布时间】:2010-12-29 22:28:03
【问题描述】:

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

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

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

tools -> create PHPUnit tests 出现以下错误:

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' )
    );
  }
}
?>

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

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

所选源文件的测试文件 没找到

有什么想法吗?

感谢

sas

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

ps2:使用 netbeans 2.8 开发版

【问题讨论】:

  • 能否给出两个文件的文件名和路径
  • 当然,刚刚编辑了问题以添加该信息...

标签: php unit-testing netbeans phpunit


【解决方案1】:

您编写单元测试用例的方式是 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 会在您的文件中查找类。然后它基于这个类和它的公共 API 创建一个测试用例,并将它称为ClassNameTest,其中ClassName 是被测试类的名称。

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

所以,我的建议是尽可能使用类。如果您有不依赖于任何东西并且在全局范围内使用的实用程序函数,请将它们设为静态函数。

旁注:我会去掉你的两个函数toUpper()toLower()。不需要时无需包装内置的 PHP 函数。也无需测试它们,因为它们已经过彻底测试。

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

【讨论】:

  • 这些日子已经一去不复返了。我想在没有 OOP 的情况下对我的 php 进行单元测试。当然,我可以手动完成。但我更愿意依赖测试框架的好处。 2017年如何使用过程式编程编写单元测试的想法?
猜你喜欢
  • 1970-01-01
  • 2012-07-01
  • 2013-08-02
  • 1970-01-01
  • 2012-04-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多