【问题标题】:PHPUnit signals a warning when mocking a namespace-ed classPHPUnit 在模拟命名空间类时发出警告
【发布时间】:2020-04-11 08:55:40
【问题描述】:

我的作曲家项目由srctests 文件夹组成。 src 中的代码是使用 composers psr4 autoloader 自动加载的,就像这样

    "autoload": {
    "psr-4": {
        "christmas\\":"src/"
    }
}

要测试的类是这样的

namespace christmas;
class Hello
{   //constructor & dependency injection included in real class

public function sayHello()
{
    return "HELLO";
}
}

最后我的测试类看起来像这样

<?php
    use PHPUnit\Framework\TestCase;
    require_once('../vendor/autoload.php');
    use christmas\Hello;


    class TestHello extends TestCase
    {
        public function testSayHelloMethod()
        {
            $hello = $this->getMockBuilder('Hello')
                ->getMock();
            $hello->expects($this->once())
                ->method('sayHello')
                ->will($this->returnValue('HELLO'));

            $this->assertEquals(
                "HELLO",
                $hello->sayHello()
            );


        }
    }

这就是我运行 phpunit 的方式

phpunit tests/TestHello

phpunit 回显以下输出

Time: 45 ms, Memory: 4.00 MB

    There was 1 warning:

    1) tests\Hello::testSayHelloMethod()
    Trying to configure method "sayHello" which cannot be configured because it does not exist, has not been specified, is final, or is static

    /usr/share/php/PHPUnit/TextUI/TestRunner.php:641
    /usr/share/php/PHPUnit/TextUI/Command.php:206
    /usr/share/php/PHPUnit/TextUI/Command.php:162

    WARNINGS!
    Tests: 1, Assertions: 0, Warnings: 1.

下面是我的代码组织方式的视图,

    ├── composer.json
    ├── src
    │   └── Hello.php
    ├── tests
    │   └── TestHello.php
    └── vendor

我错过了什么?我需要通过没有任何警告的通过测试。

【问题讨论】:

    标签: php composer-php autoloader phpunit


    【解决方案1】:

    您需要将类的完整命名空间名称传递给模拟构建器,即'christmas\Hello'。由于您需要将其作为字符串传递,因此仅使用“Hello”不足以正确识别该类。

    由于您已经拥有该类的use,因此您可以使用::class 来获取全名。例如:

    $hello = $this->getMockBuilder(Hello::class)
                    ->getMock();
    

    【讨论】:

    • 感谢@Peter,添加完整的命名空间工作 christmas\HelloHello::class 也可以完美运行。谢谢!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多