sebastianbergmann/phpunit · error · RuntimeException

Return value for %s::%s() cannot be generated: %s

Error message

Return value for %s::%s() cannot be generated: %s

What it means

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.

Source

Thrown at src/Framework/MockObject/Runtime/ReturnValueGenerator.php:195

    private function newInstanceOf(StubInternal $testStub, string $className, string $methodName): Stub
    {
        try {
            $object    = new ReflectionClass($testStub::class)->newInstanceWithoutConstructor();
            $reflector = new ReflectionObject($object);

            $reflector->getProperty('__phpunit_state')->setValue(
                $object,
                new TestDoubleState(
                    $testStub->__phpunit_state()->configurableMethods(),
                    $className,
                    $testStub->__phpunit_state()->generateReturnValues(),
                ),
            );

            return $object;
            // @codeCoverageIgnoreStart
        } catch (Throwable $t) {
            throw new RuntimeException(
                sprintf(
                    'Return value for %s::%s() cannot be generated: %s',
                    $className,
                    $methodName,
                    $t->getMessage(),
                ),
            );
            // @codeCoverageIgnoreEnd
        }
    }

    /**
     * @param class-string     $type
     * @param class-string     $className
     * @param non-empty-string $methodName
     *
     * @throws RuntimeException
     */

View on GitHub (pinned to f123cdb2a2)

Solutions

  1. Configure an explicit return: ->method('createTime')->willReturn(new DateTimeImmutable('2024-01-01 00:00:00')).
  2. Or use ->willReturnCallback(fn () => new Entity(...)) with valid constructor arguments.
  3. If construction legitimately fails in tests, provide a test-specific instance instead of relying on auto-generation.
  4. Consider making the constructor test-friendly (named constructors) upstream if this recurs.

Example fix

// before
$factory = $this->createStub(Factory::class);
$item = $factory->make(); // make(): Item, Item::__construct() throws

// after
$factory = $this->createStub(Factory::class);
$factory->method('make')->willReturn(new Item('test-id'));
$item = $factory->make();
Defensive patterns

Strategy: validation

Validate before calling

// for class-typed returns with non-trivial constructors, stub explicitly
$rm = new ReflectionMethod(Factory::class, 'make');
$type = (string) $rm->getReturnType();
if (class_exists($type) && (new ReflectionClass($type))->getConstructor()?->getNumberOfRequiredParameters() > 0) {
    $stub->method('make')->willReturn(new $type(/* valid args */));
}

Type guard

function canAutoInstantiate(ReflectionClass $class): bool
{
    $ctor = $class->getConstructor();

    return $class->isInstantiable()
        && ($ctor === null || $ctor->getNumberOfRequiredParameters() === 0);
}

Try / catch

try {
    $subject->run($stub);
} catch (PHPUnit\Framework\MockObject\RuntimeException $e) {
    // underlying constructor error is appended — provide a prebuilt instance instead
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of sebastianbergmann/phpunit@f123cdb2a2 (2026-08-23). Data as JSON: /api/errors/cdb6e477f26b804c. Report an issue: GitHub.