{"record":{"id":"3ed5cf0c948bbe68","repo":"sebastianbergmann/phpunit","slug":"expectation-for-s-failed-s","errorCode":null,"errorMessage":"Expectation for %s failed.\n%s","messagePattern":"Expectation for (.+?) failed\\.\n(.+?)","errorType":"exception","errorClass":"ExpectationFailedException","httpStatus":null,"severity":"error","filePath":"src/Framework/MockObject/Runtime/Matcher.php","lineNumber":139,"sourceCode":"            throw new MethodNameNotConfiguredException;\n        }\n\n        if ($this->afterMatchBuilderId !== null) {\n            $matcher = $invocation->object()\n                ->__phpunit_getInvocationHandler()\n                ->lookupMatcher($this->afterMatchBuilderId);\n\n            if ($matcher === null) {\n                throw new MatchBuilderNotFoundException($this->afterMatchBuilderId);\n            }\n        }\n\n        $this->invocationRule->invoked($invocation);\n\n        try {\n            $this->parametersRule?->apply($invocation);\n        } catch (ExpectationFailedException $e) {\n            throw new ExpectationFailedException(\n                sprintf(\n                    \"Expectation for %s failed.\\n%s\",\n                    $this->methodNameRule->failureDescription($this->className),\n                    $e->getMessage(),\n                ),\n                $e->getComparisonFailure(),\n            );\n        }\n\n        if ($this->stub !== null) {\n            return $this->stub->invoke($invocation);\n        }\n\n        return $invocation->generateReturnValue();\n    }\n\n    /**\n     * @throws ExpectationFailedException","sourceCodeStart":121,"sourceCodeEnd":157,"githubUrl":"https://github.com/sebastianbergmann/phpunit/blob/f123cdb2a2d49f15025794166cfed8bda8627dd2/src/Framework/MockObject/Runtime/Matcher.php#L121-L157","documentation":"Wrapped ExpectationFailedException from Matcher::invoked(): when a real call arrives and the matcher's parametersRule->apply($invocation) fails (the actual arguments do not satisfy with() constraints), PHPUnit rethrows with 'Expectation for <method> failed.' prefixed to the original parameter mismatch message, preserving the comparison failure. It means the method was called, but with different arguments than the expectation asserts.","triggerScenarios":"Expectation ->method('transfer')->with(100, 'EUR') but the code under test calls transfer(50, 'EUR'); identical() vs equalTo() semantics (with() defaults to equal, not same) so same-looking objects differ; float/string coercion mismatches under strict comparison inside the parameter rule.","commonSituations":"The subject transforms arguments before delegating to the collaborator (multiplied amounts, trimmed strings, wrapped DTOs); expectations copied from a spec where values were different; with(new Money(100)) comparing object identity instead of equality; timezone/locale formatting changing string arguments.","solutions":["Read the nested message: it shows the expected vs actual argument values — align the expectation with the real arguments (or fix the production code that passes wrong ones).","For object arguments, either implement value equality on the DTO or use a callback constraint: ->with($this->callback(fn ($m) => $m->amount === 100)).","Use $this->identicalTo($x) when identity is the real requirement, and $this->equalTo($x) (default) for structural equality.","If argument order varies, withParameterSetsInAnyOrder([...]) replaces several brittle with() rules."],"exampleFix":"// before\n$mailer = $this->createMock(Mailer::class);\n$mailer->expects($this->once())\n    ->method('send')\n    ->with('Hello') // code actually sends 'Hello!' \n    ->willReturn(true);\n\n// after\n$mailer->expects($this->once())\n    ->method('send')\n    ->with('Hello!')\n    ->willReturn(true);","handlingStrategy":"try-catch","validationCode":"// pre-check the exact constraint against the value you expect the subject to pass\n$expected = 'Hello!';\n$actual = $subject->buildGreeting();\n$this->assertSame($expected, $actual); // fail early with a clean diff before the mock call","typeGuard":"// constraints double as guards: verify a value satisfies the with() rule before the call\n$constraint = $this->identicalTo($token);\nif (!$constraint->evaluate($candidate, '', true)) {\n    throw new RuntimeException('subject will pass a different token');\n}","tryCatchPattern":"try {\n    $subject->run($mock);\n} catch (PHPUnit\\Framework\\ExpectationFailedException $e) {\n    // assertion failure during the call: inspect getComparisonFailure() diff,\n    // fix the with() constraints to match reality, then remove the catch\n}","preventionTips":["Read the nested message — it contains expected vs actual argument values; align the expectation with reality.","For object arguments, use callback constraints comparing fields instead of relying on equality/identity surprises.","Avoid literals for runtime-computed arguments (timestamps, ids); constrain structurally."],"tags":["phpunit","mock-object","with","argument-mismatch","expectation-failed"],"backgroundTag":"mock-argument-mismatch","analyzedSha":"f123cdb2a2d49f15025794166cfed8bda8627dd2","analyzedAt":"2026-08-23T01:20:58.058Z","schemaVersion":2},"datasetVersion":"2026-08-23T08:06:27.607Z"}