代码之家  ›  专栏  ›  技术社区  ›  opensas

用netbeans和phpunit测试PHP函数(不是类)

  •  6
  • opensas  · 技术社区  · 15 年前

    我想运行函数库文件的单元测试…

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

    例如,我在~/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测试时出现以下错误:

    塞巴斯蒂安·伯格曼的《普普林特3.4.5》。

    在中找不到类“format” “/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

    另一个问题是,是否有一种方法可以更新生成的测试而不必手动删除它们?你说什么?

    PS2:使用NetBeans 2.8 dev

    1 回复  |  直到 15 年前
        1
  •  5
  •   Stephen Melrose    15 年前

    您如何编写单元测试用例是100%正确的。问题在于共同的约定,以及phpunit和netbean是如何依赖它们的。

    现在的最佳实践是以面向对象的方式编写所有代码。因此,不要像您所拥有的那样拥有一个充满实用函数的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 是要测试的类的名称。

    各国也遵守本公约,并知道 最高级的 是phpunit测试用例 类名 ,因此在IDE中创建两个链接。

    所以,我的建议是尽可能多地使用课程。如果您有不依赖任何东西的实用程序函数,并且它们是全局使用的,那么就让它们成为静态函数。

    边注: 我会取消你的两项职能 toUpper() toLower() .不需要包装内置的PHP函数。也没有必要测试它们,因为它们经过了彻底的测试。

    网站注释2: 有一种内置的PHP等价于您的函数 toProper() 打电话 ucfirst() .