I have a simple test where I mock a dependency of the code under test:
<?php
use PHPUnit\Framework\TestCase;
class Dependency {
public function someFunction(int $first, int $second): int {
return $first + $second;
}
}
class CodeUnderTest {
public function testMe(Dependency $dep, int $first, int $second): int {
return $dep->someFunction($first, $second);
}
}
class TheTest extends TestCase
{
public final function testMe(): void {
$dep = $this->createMock(Dependency::class);
$dep->expects(self::once())->method('someFunction')->with(second: 2, first: 1)->willReturn(3);
$codeUnderTest = new CodeUnderTest();
$codeUnderTest->testMe($dep, 1, 2);
}
}
This fails:
Expectation failed for method name is "someFunction" when invoked 1 time(s)
Parameter 0 for invocation Dependency::someFunction(1, 2): int does not match expected value.
Failed asserting that 1 matches expected 2.
Expected :2
Actual :1
Why does this happen? My mock object clearly defines the expected values, even by name.
Looks like phpunit does not handle named arguments and silently ignores them.
$dep->expects(self::once())->method('someFunction')->with(1, 2)->willReturn(3);
makes the test pass.
With that it's probably better to not use named arguments in the with
call.