【问题标题】:Php Unit not finding classPHP单元找不到类
【发布时间】:2014-07-14 04:24:50
【问题描述】:

我正在使用 PHPUnit,并且在我的测试中遇到未定义的方法错误。我在位于 /Applications/MAMP/htdocs/stats/includes/models/Stats.php 的文件夹中嵌套了以下类:

namespace stats\includes\models;

class Stats
 {  
 public function sluggify($string, $separator = '-', $maxLength = 96)
    {
    $title = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
    $title = preg_replace("%[^-/+|\w ]%", '', $title);
    $title = strtolower(trim(substr($title, 0, $maxLength), '-'));
    $title = preg_replace("/[\/_|+ -]+/", $separator, $title);

    return $title;
   }
 }

我的单元测试位于 /Applications/MAMP/htdocs/stats/Test/createTest.php 我的单元测试代码如下:

namespace stats\Test;

require '/Applications/MAMP/htdocs/stats/includes/models/Stats.php';

class StatsTest extends \PHPUnit_Framework_TestCase
{

 public function testSluggifyReturnsSluggifiedString()
  {
    $originalString = 'This string will be sluggified';
    $expectedResult = 'this-string-will-be-sluggified';

    $url = new Stats();

    $result = $url->sluggify($originalString);

    $this->assertEquals($expectedResult, $result);
 }

如果我成功地要求该类,为什么我的方法未定义?

【问题讨论】:

  • “为什么我的方法未定义”---这是什么意思?
  • 函数“sluggify”没有定义。
  • 您似乎忽略了您收到的实际错误消息。另外,Stats 是否在命名空间中?
  • 这是我的错误:PHP 致命错误:调用未定义的方法 stats\Test\StatsTest::sluggify()
  • Stats 类具有以下命名空间:namespace stats\includes\models;

标签: php unit-testing phpunit


【解决方案1】:

您的测试类位于命名空间 stats\Test 中,而您的 Stats 类位于 stats\includes\models 命名空间中。

createTest.phpnamespace 声明下添加此内容

use stats\includes\models\Stats;

或者干脆使用

$url = new \stats\includes\models\Stats();

在您的测试方法中。

附录

为您的类及其测试使用相同的命名空间以及在其中的测试套件之后命名您的测试文件(即StatsTest.php 而不是createTest.php)是一个相当普遍的约定。

我建议你看看 GitHub 上的其他一些大型 PHP 项目,并特别注意他们的测试套件。

【讨论】:

    猜你喜欢
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2014-02-25
    • 2017-05-24
    • 2015-04-04
    • 2021-09-20
    • 2012-05-04
    相关资源
    最近更新 更多