【问题标题】:PHPUnit 9 - Mocking void methodsPHPUnit 9 - 模拟 void 方法
【发布时间】:2021-04-27 10:01:42
【问题描述】:

我刚刚将phpunit 7.5.20 升级到phpunit 9.5.0,我遇到了很多错误(实际上是好的),但不能100% 确定如何解决其中的一些错误。 只是寻找一些想法来解决以下错误:

Method setDummyStuff may not return value of type NULL, its return declaration is "void"

仅当您创建 createConfiguredMock() 并将 null 方法作为参数传递时才会发生这种情况。

这是我的测试:

<?php


use Lib\IDummyCode;

class DummyTest extends PHPUnit\Framework\TestCase
{
    public function setUp(): void
    {
        parent::setUp();
    }

    public function testDummyThatReturnsVoid()
    {
        $this->createConfiguredMock(IDummyCode::class, [
            'setDummyStuff' => null
        ]);
    }
}

这是虚拟类:

<?php


namespace Lib;

interface IDummyCode
{
    public function setDummyStuff(
        int $testInt,
        string $testString
    ): void;
}

你们对如何改进这个有一些想法吗? 非常感谢!

【问题讨论】:

    标签: unit-testing methods mocking phpunit


    【解决方案1】:

    createConfiguredMock 的第二个参数采用关联数组,其中键是要模拟的方法,值是方法应返回的值。由于setDummyStuff 方法不能返回任何东西(void 返回类型),因此定义返回值是没有意义的。这不是null 值。任何值都会失败。

    所以你可以忽略那个方法:

    $mock = $this->createConfiguredMock(IDummyCode::class, []);
    

    这也可以写成更好的方式:

    $mock = $this->createStub(IDummyCode::class);
    

    如果您需要验证 setDummyStuff 是否被调用,则必须设置期望。

    $mock = $this->createMock(IDummyCode::class);
    $mock->expects(self::once())
         ->method('setDummyStuff')
         ->with(123, 'Hello');
    

    【讨论】:

    • 太棒了@PhilipWeinke!你解决我的问题。我正在重构/升级整个测试套件,我注意到我在许多测试中描述的方法:(这是修复测试并重新教育其他开发人员如何处理 void 方法的好机会。再次感谢.
    • 很高兴能帮上忙
    猜你喜欢
    • 2013-01-27
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多