Skip to content

Incorrect behavior of WithConsecutiveRector: variables in willReturnOnConsecutiveCalls() not added to closure use() #9962

Closed
rectorphp/rector-phpunit
#821

Description

@bbrala

Bug Report

Subject Details
Rector version 2.8.4 (also checked rector-phpunit main @ d32a17a)
Installed as composer dependency

Minimal PHP Code Causing Issue

<?php

final class DemoTest extends PHPUnit\Framework\TestCase
{
    public function test(): void
    {
        $title = new \stdClass();

        $this->manager->expects($this->exactly(2))
            ->method('getFieldDefinitions')
            ->withConsecutive(['first'], ['second'])
            ->willReturnOnConsecutiveCalls(['title' => $title], []);
    }
}

Current output:

        $matcher = $this->exactly(2);
        $this->manager->expects($matcher)
            ->method('getFieldDefinitions')->willReturnCallback(function (...$parameters) use ($matcher) {
                if ($matcher->numberOfInvocations() === 1) {
                    $this->assertSame('first', $parameters[0]);
                    return ['title' => $title];
                }
                if ($matcher->numberOfInvocations() === 2) {
                    $this->assertSame('second', $parameters[0]);
                    return [];
                }
            });

$title is used in the closure but not captured, so the test now fails with "Undefined variable $title".

Responsible rules

  • WithConsecutiveRector

Expected Behavior

Variables used in the willReturnOnConsecutiveCalls() arguments should be added to the closure's use(), like variables from withConsecutive() and willReturn() already are:

function (...$parameters) use ($matcher, $title) {

Looks like UsedVariablesResolver::resolveUsedVariables() only looks at the withConsecutive() call and the single return statement, while WillReturnIfNodeDecorator adds the willReturnOnConsecutiveCalls() values afterwards.

Found in the wild in Drupal's lingotek module (tests/src/Unit/Plugin/RelatedEntitiesDetector/NestedErViewmodeEntitiesDetectorTest.php) while running Rector over all Drupal contrib projects.

Activity

  1. TomasVotruba commented on Nov 9, 2026

    @TomasVotruba
    Member

    Thanks for reporting 👍

    Fixed in rectorphp/rector-phpunit#821

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions