【问题标题】:PHPUnit_Framework_Assert::assertClassHasStaticAttribute() must be a class namePHPUnit_Framework_Assert::assertClassHasStaticAttribute() 必须是类名
【发布时间】:2016-02-07 10:32:35
【问题描述】:

我刚开始学习 PHPUnit。我有一个看似很简单的测试;

namespace stats\Test;

use stats\Fetch;

class FetchTest extends \PHPUnit_Framework_TestCase
{

    public function setUp()
    {
        $this->fetch = new Fetch;
    }

    public function testStoresListOfAssets()
    {
        $this->assertClassHasStaticAttribute('paths', 'Fetch'); //line 17
    }

}

我的 Fetch 类是;

namespace stats;

class Fetch
{
    public static $paths = array(
        'jquery' => 'http://code.jquery.com/jquery.js'
    );
}

我在运行 PHPUnit 时遇到的错误; PHPUnit_Framework_Exception: Argument #2 (string#Fetch)of PHPUnit_Framework_Assert::assertClassHasStaticAttribute() must be a class name

这可能是非常愚蠢的事情,但我无法理解问题

【问题讨论】:

    标签: php phpunit


    【解决方案1】:

    PHPUnit_Framework_Assert 使用 PHP 方法 class_exists 来检查您指定的类名是否正确(查看this link 以查看完整代码):

    if (!is_string($className) || !class_exists($className, FALSE)) {
      throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'class name');
    }
    

    你在这里遇到的问题是方法 class_exists 没有考虑到这个命令:

    use stats\Fetch;
    

    因此,您必须指明完整路径才能使其正常工作。在this link of stackoverflow,您可以找到有关该问题的更多信息。你应该把你的断言改成这样:

    $this->assertClassHasStaticAttribute('paths', '\\stats\\Fetch');

    【讨论】:

    • 大约 30 秒前我自己偶然发现了这个答案。我刚试过'stats\Fetch',它奏效了。感谢您提供正确的答案
    【解决方案2】:

    您没有提供完全限定的类名,并且在 assertClassHasStaticAttribute() 或您的(测试)类范围之外的任何其他方法/函数的上下文中,使用补充类名的语句。

    如果您使用的是 PHP 5.5 或更高版本(您应该这样做),请使用 Fetch::class

    一般来说,您应该更喜欢 ::class 而不是字符串作为类名,因为现代 IDE 可以帮助您在更改类名时进行重构,如果您使用字符串,这几乎是不可能的。

    总而言之,以您的示例为例:

    public function testStoresListOfAssets()
    {
        $this->assertClassHasStaticAttribute('paths', Fetch::class);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 2015-12-16
      • 1970-01-01
      • 2020-02-02
      • 2019-06-20
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多