1

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.

2
  • Have you tried it with the arguments in the order with(first: 1, second: 2) - could be that it works with field by position rather than using names. Commented Apr 19 at 9:57
  • @NigelRen Yes, that's exactly what it does. Very confusing. Commented Apr 19 at 20:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

if it helps for some more insight: with(second: 2, first: 1) would mean that the with() method would have two named parameters: second and first. but my guess is that your mocked method has those. AFAIK this cannot be that easily done --if at all (from the perspective from inside that with() method).
It happends too with willReturnMap ? ---> I'm trying to use : --> $themock->willReturnMap([['9001', 'arg3' => 'a', 'a', ['9007', 'arg2' => 'B', 'B]]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.