Everton Wcks
Everton Wcks

Reputation: 109

PHPUnit 9 - Mocking void methods

I just upgraded the phpunit 7.5.20 to phpunit 9.5.0 and I'm facing a lot of errors (good ones actually), but not 100% sure how to workaround with some of those errors. Just looking for some ideas to fix the following error:

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

It happens only when you're creating a createConfiguredMock() and passing a null method as a argument.

Here's my test:

<?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
        ]);
    }
}

And here's the dummy class:

<?php


namespace Lib;

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

Do you guys, have some thoughts about how to improve this? Thanks a lot!

Upvotes: 7

Views: 13756

Answers (1)

Philip Weinke
Philip Weinke

Reputation: 1844

The second parameter to createConfiguredMock takes an associative array where the key is the method to mock and the value is the value the method should return. Since the setDummyStuff method can not return anything (void return type) it does not make sense to define a return value. It isn't the null value in particular. It will fail with any value.

So you could just leave that method out:

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

Which can also be written in a nicer way:

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

If you need to verify that setDummyStuff was called, you have to set up an expectation.

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

Upvotes: 10

Related Questions