PHPUnit returnValueMap method does not work: returns NULL
It happens that a method mocking with returnValueMap returns NULL. Sometimes this happens because the returnValueMap method does not specify all the arguments that exist in the signature of the method being replaced. Usually, you can miss out on optional arguments.
Example:
<?php
namespace Tests\ExampleProject;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
public function testSomething()
{
$mockObject = $this->createMock(DummyObject::class);
$mockObject
->method('someMethod')
->will($this->returnValueMap([
['a', 'b', 't'],
]));
$this->assertEquals('t', $mockObject->someMethod('a', 'b'));
}
}
class DummyObject
{
public function someMethod($x, $y, $z = null) {}
}
You can see, than optional argument $z isnot specified.
Test result:
PHPUnit 7.0.3 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 19 ms, Memory: 4.00MB
There was 1 failure:
1) Tests\ExampleProject\ExampleTest::testSomething
Failed asserting that null matches expected 't'.
/home/ohorzin/projects/workbench/exa.php:18
FAILURES!
Tests: 1, Assertions: 1, Failures: 1
You can see, thattestSomething method returns NULL. It looks like whentestSomething method is not mocked
Let's fix the test:
<?php
namespace Tests\ExampleProject;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
public function testSomething()
{
$mockObject = $this->createMock(DummyObject::class);
$mockObject
->method('someMethod')
->will($this->returnValueMap([
['a', 'b', 'c', 't'],
]));
$this->assertEquals('t', $mockObject->someMethod('a', 'b', 'c'));
}
}
class DummyObject
{
public function someMethod($x, $y, $z = null) {}
}
Test result:
PHPUnit 7.0.3 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 24 ms, Memory: 4.00MB
OK (1 test, 1 assertion)
It works!In other cases, the error may be that the specified values in returnValueMap do not match those that are passed in reality.