{"record":{"id":"cdb6e477f26b804c","repo":"sebastianbergmann/phpunit","slug":"return-value-for-s-s-cannot-be-generated-s","errorCode":null,"errorMessage":"Return value for %s::%s() cannot be generated: %s","messagePattern":"Return value for (.+?)::(.+?)\\(\\) cannot be generated: (.+?)","errorType":"exception","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"src/Framework/MockObject/Runtime/ReturnValueGenerator.php","lineNumber":195,"sourceCode":"    private function newInstanceOf(StubInternal $testStub, string $className, string $methodName): Stub\n    {\n        try {\n            $object    = new ReflectionClass($testStub::class)->newInstanceWithoutConstructor();\n            $reflector = new ReflectionObject($object);\n\n            $reflector->getProperty('__phpunit_state')->setValue(\n                $object,\n                new TestDoubleState(\n                    $testStub->__phpunit_state()->configurableMethods(),\n                    $className,\n                    $testStub->__phpunit_state()->generateReturnValues(),\n                ),\n            );\n\n            return $object;\n            // @codeCoverageIgnoreStart\n        } catch (Throwable $t) {\n            throw new RuntimeException(\n                sprintf(\n                    'Return value for %s::%s() cannot be generated: %s',\n                    $className,\n                    $methodName,\n                    $t->getMessage(),\n                ),\n            );\n            // @codeCoverageIgnoreEnd\n        }\n    }\n\n    /**\n     * @param class-string     $type\n     * @param class-string     $className\n     * @param non-empty-string $methodName\n     *\n     * @throws RuntimeException\n     */","sourceCodeStart":177,"sourceCodeEnd":213,"githubUrl":"https://github.com/sebastianbergmann/phpunit/blob/f123cdb2a2d49f15025794166cfed8bda8627dd2/src/Framework/MockObject/Runtime/ReturnValueGenerator.php#L177-L213","documentation":"Thrown by ReturnValueGenerator::newInstanceOf(): while auto-generating a default return for a method whose return type is a concrete class, instantiating that class via reflection threw (constructor raised, promoted property validation failed, etc.). The wrapper keeps the class::method context and appends the underlying constructor error message; the block is marked @codeCoverageIgnore because it only triggers on misbehaving constructors.","triggerScenarios":"A stubbed method typed to return a class whose constructor throws for default arguments (e.g. new DateTimeImmutable('bad format') style validation, entities with invariant checks); value objects that reject zero-argument instantiation; constructors requiring ext/service side effects (database handle) that fail in the test environment.","commonSituations":"Domain objects with guarded constructors used as return types; constructors that call out to env/config not set up in tests; entities with readonly promoted properties that validate; defaults relying on services removed in the test bootstrap.","solutions":["Configure an explicit return: ->method('createTime')->willReturn(new DateTimeImmutable('2024-01-01 00:00:00')).","Or use ->willReturnCallback(fn () => new Entity(...)) with valid constructor arguments.","If construction legitimately fails in tests, provide a test-specific instance instead of relying on auto-generation.","Consider making the constructor test-friendly (named constructors) upstream if this recurs."],"exampleFix":"// before\n$factory = $this->createStub(Factory::class);\n$item = $factory->make(); // make(): Item, Item::__construct() throws\n\n// after\n$factory = $this->createStub(Factory::class);\n$factory->method('make')->willReturn(new Item('test-id'));\n$item = $factory->make();","handlingStrategy":"validation","validationCode":"// for class-typed returns with non-trivial constructors, stub explicitly\n$rm = new ReflectionMethod(Factory::class, 'make');\n$type = (string) $rm->getReturnType();\nif (class_exists($type) && (new ReflectionClass($type))->getConstructor()?->getNumberOfRequiredParameters() > 0) {\n    $stub->method('make')->willReturn(new $type(/* valid args */));\n}","typeGuard":"function canAutoInstantiate(ReflectionClass $class): bool\n{\n    $ctor = $class->getConstructor();\n\n    return $class->isInstantiable()\n        && ($ctor === null || $ctor->getNumberOfRequiredParameters() === 0);\n}","tryCatchPattern":"try {\n    $subject->run($stub);\n} catch (PHPUnit\\Framework\\MockObject\\RuntimeException $e) {\n    // underlying constructor error is appended — provide a prebuilt instance instead\n}","preventionTips":["Prefer supplying real, valid instances via willReturn() for value objects over relying on generation.","Audit stubbed methods whose return types have constructors with required parameters or side effects.","Construct domain objects with test data in helpers so defaults never hit guarded constructors."],"tags":["phpunit","mock-object","return-value-generation","constructor-error","reflection"],"backgroundTag":"missing-stub-return-value","analyzedSha":"f123cdb2a2d49f15025794166cfed8bda8627dd2","analyzedAt":"2026-08-23T01:20:58.058Z","schemaVersion":2},"datasetVersion":"2026-08-23T08:06:27.607Z"}