Unit testing PHPUnit 9-模拟无效方法

Unit testing PHPUnit 9-模拟无效方法,unit-testing,methods,mocking,phpunit,Unit Testing,Methods,Mocking,Phpunit,我刚刚将phpunit 7.5.20升级到phpunit 9.5.0,我遇到了很多错误(实际上是好的错误),但我不能100%确定如何解决其中的一些错误。 正在寻找一些解决以下错误的方法: 方法setDummyStuff不能返回NULL类型的值,其返回声明为“void” 只有在创建createConfiguredMock()并将null方法作为参数传递时,才会发生这种情况 这是我的测试: <?php use Lib\IDummyCode; class DummyTest extends

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

方法setDummyStuff不能返回NULL类型的值,其返回声明为“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
        ]);
    }
}

createConfiguredMock
的第二个参数采用关联数组,其中键是要模拟的方法,值是该方法应返回的值。由于
setDummyStuff
方法不能返回任何内容(void return type),因此定义返回值没有意义。特别是
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');

太棒了@Philipweink!你解决了我的问题。我正在重构/升级整个测试套件,我注意到我在许多测试中描述的方法:(这是修复测试并重新教育其他开发人员如何处理无效方法的绝佳机会。再次感谢。我很高兴能提供帮助
$mock = $this->createMock(IDummyCode::class);
$mock->expects(self::once())
     ->method('setDummyStuff')
     ->with(123, 'Hello');