Skip to content

Add ExpectsParamToMockObjectRector for private test method params - #753

Merged
TomasVotruba merged 1 commit into
mainfrom
expects-param-to-mock-object
Jul 31, 2026
Merged

Add ExpectsParamToMockObjectRector for private test method params#753
TomasVotruba merged 1 commit into
mainfrom
expects-param-to-mock-object

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Adds ExpectsParamToMockObjectRector (PHPUnit 11+), that changes the param type of a private test-case method to MockObject, when expects() is called on that param.

Since PHPUnit 10, expects() only exists on MockObject, not on the plain class type. Passing a mock into a helper method typed with the original class forces @phpstan-ignore-next-line on every expects() call:

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
-    private function prepareUserMock(SomeUser $user): void
+    private function prepareUserMock(\PHPUnit\Framework\MockObject\MockObject $user): void
     {
-        // @phpstan-ignore-next-line
         $user->expects($this->once())
             ->method('getId')
             ->willReturn(1);
     }
 }

(the rule only changes the type; leftover ignore comments are removed by other tooling)

Only params with an actual expects() call are changed:

-    private function prepareUserMock(SomeUser $user, SomeUser $anotherUser): void
+    private function prepareUserMock(\PHPUnit\Framework\MockObject\MockObject $user, SomeUser $anotherUser): void
     {
         $anotherUser->getId();

         $user->expects($this->once())
             ->method('getId');
     }

Skipped:

  • non-private methods, as those can be called from outside the test case
  • params already typed MockObject, incl. intersection types like SomeUser&MockObject
  • params with a @param docblock tag, to avoid a native type contradicting the docblock
  • classes that are not test cases

Registered in the composer-based set, bound to phpunit/phpunit >=11.0, next to the related MockObjectArgCreateStubToCreateMockRector.

@TomasVotruba
TomasVotruba merged commit 254bbf1 into main Jul 31, 2026
7 checks passed
@TomasVotruba
TomasVotruba deleted the expects-param-to-mock-object branch July 31, 2026 21:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant