Find the best Rector rule to solve your problem. Searching through 823 rules.

Found 100 rules:

FinalizeTestCaseClassRector

Make PHPUnit test case final

 use PHPUnit\Framework\TestCase;

-class SomeClass extends TestCase
+final class SomeClass extends TestCase
 {
 }
SETS:  Code Quality

ExplicitMockExpectsCallRector

Add explicit expects() to method() mock calls, to make expectations count explicit

 use PHPUnit\Framework\TestCase;

 final class SomeClass extends TestCase
 {
     public function testMe()
     {
         $someMock = $this->createMock(\stdClass::class);
-        $someMock->method('some');
+        $someMock->expects($this->atLeastOnce())->method('some');
     }
 }

CreateStubInCoalesceArgRector

Use createStub() over createMock() when used as argument/array item coalesce ?? fallback

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $mockObject = $this->>get('service');
-        $this->someMethod($mockObject ?? $this->createMock(SomeClass::class));
+        $this->someMethod($mockObject ?? $this->createStub(SomeClass::class));
     }

     private function someMethod($someClass)
     {
-    }
 }

CreateStubOverCreateMockArgRector

Use createStub() over createMock() when used as argument or array value and does not add any mock requirements

 use PHPUnit\Framework\TestCase;
+
 final class SomeTest extends TestCase
 {
     public function test()
     {
-        $this->someMethod($this->createMock(SomeClass::class));
+        $this->someMethod($this->createStub(SomeClass::class));
     }

     private function someMethod($someClass)
     {
     }
 }

RemoveOverrideFinalConstructTestCaseRector

Remove override final construct test case

 use PHPUnit\Framework\TestCase;

 final class SomeClass extends TestCase
 {
-    public function __construct()
-    {
-        parent::__construct(static::class);
-    }
 }

AllowMockObjectsForDataProviderRector

Add #[AllowMockObjectsWithoutExpectations] attribute to PHPUnit test classes that have methods with data providers and mock objects without expectations

 use PHPUnit\Framework\Attributes\DataProvider;
 use PHPUnit\Framework\TestCase;

+#[\PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations]
 final class SomeClass extends TestCase
 {
     #[DataProvider('someDataProvider')]
     public function test()
     {
         $someMock = $this->createMock(\stdClass::class);
         $someMock->expects('method')->willReturn(true);
     }

     public static function someDataProvider(): iterable
     {
         yield [1];
         yield [2];
         yield [3];
     }
 }

AllowMockObjectsWhereParentClassRector

Add #[AllowMockObjectsWithoutExpectations] attribute to PHPUnit test classes with a 3rd party test case, that provides any mocks

 use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

+#[\PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations]
 final class SomeTest extends ConstraintValidatorTestCase
 {
 }

PropertyCreateMockToCreateStubRector

Change mock object property that is never mocked to createStub()

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
-    private \PHPUnit\Framework\MockObject\MockObject $someServiceMock;
+    private \PHPUnit\Framework\MockObject\Stub\Stub $someServiceMock;

     protected function setUp(): void
     {
-        $this->someServiceMock = $this->createMock(SomeService::class);
+        $this->someServiceMock = $this->createStub(SomeService::class);
     }

     public function testOne(): void
     {
         $someObject = new SomeClass($this->someServiceMock);
     }

     public function testTwo(): void
     {
         $someObject = new AnotherClass($this->someServiceMock);
     }
 }

AssertIsTypeMethodCallRector

Replaces Assert::isType() calls with type-specific Assert::is*() calls

 use PHPUnit\Framework\TestCase;

 final class SomeClass extends TestCase
 {
     public function testMethod(): void
     {
-        $this->assertThat([], $this->isType('array'));
+        $this->assertThat([], $this->isArray());
     }
 }

AllowMockObjectsWithoutExpectationsAttributeRector

Add #[AllowMockObjectsWithoutExpectations] attribute to PHPUnit test classes with mock properties used in multiple methods but one, to avoid irrelevant notices in tests run

 use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
+
+#[AllowMockObjectsWithoutExpectations]
 final class SomeTest extends TestCase
 {
     private \PHPUnit\Framework\MockObject\MockObject $someServiceMock;

     protected function setUp(): void
     {
         $this->someServiceMock = $this->createMock(SomeService::class);
     }

     public function testOne(): void
     {
-        // use $this->someServiceMock
+        $this->someServiceMock->expects($this->once())
+            ->method('someMethod')
+            ->willReturn('someValue');
     }

     public function testTwo(): void
     {
-        // use $this->someServiceMock
+        $this->someServiceMock->expects($this->once())
+            ->method('someMethod')
+            ->willReturn('anotherValue');
     }
 }

ExpressionCreateMockToCreateStubRector

Replace createMock() assigned to variable that is only used as arg with no expectations, to createStub()

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test(): void
     {
-        $mock = $this->createMock(SomeClass::class);
+        $mock = $this->createStub(SomeClass::class);

         $someObject = new SomeClass($mock);
         $this->assertSame($mock, $someObject->getDependency());
     }
 }

TicketAnnotationToAttributeRector

Change annotations with value to attribute

 use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\Ticket;

-/**
- * @ticket 123
- */
+#[Ticket('123')]
 final class SomeTest extends TestCase
 {
 }

CoversAnnotationWithValueToAttributeRector

Change covers annotations with value to attribute

 use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversFunction;

-/**
- * @covers SomeClass
- */
+#[CoversClass(SomeClass::class)]
+#[CoversFunction('someFunction')]
 final class SomeTest extends TestCase
 {
-    /**
-     * @covers ::someFunction()
-     */
     public function test()
     {
     }
 }

RequiresAnnotationWithValueToAttributeRector

Change Requires annotations with values to attributes

 use PHPUnit\Framework\TestCase;

-/**
- * @requires PHP > 8.4
- * @requires PHPUnit >= 10
- */
-
+#[\PHPUnit\Framework\Attributes\RequiresPhp('> 8.4')]
+#[\PHPUnit\Framework\Attributes\RequiresPhpunit('>= 10')]
 final class SomeTest extends TestCase
 {
-    /**
-     * @requires setting date.timezone Europe/Berlin
-     */
+    #[\PHPUnit\Framework\Attributes\RequiresSetting('date.timezone', 'Europe/Berlin')]
     public function test()
     {
     }
 }

Configurable

AnnotationWithValueToAttributeRector

Change annotations with value to attribute

 use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\BackupGlobals;

-/**
- * @backupGlobals enabled
- */
+#[BackupGlobals(true)]
 final class SomeTest extends TestCase
 {
 }

DependsAnnotationWithValueToAttributeRector

Change depends annotations with value to attribute

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function testOne() {}

-    /**
-     * @depends testOne
-     */
+    #[\PHPUnit\Framework\Attributes\Depends('testOne')]
     public function testThree(): void
     {
     }
 }

TestWithAnnotationToAttributeRector

Change @testWith() annotation to #[TestWith] attribute

 use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\TestWith;

 final class SomeFixture extends TestCase
 {
-    /**
-     * @testWith ["foo"]
-     *           ["bar"]
-     */
+    #[TestWith(['foo'])]
+    #[TestWith(['bar'])]
     public function test(): void
     {
     }
 }

DataProviderAnnotationToAttributeRector

Change dataProvider annotations to attribute

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
-    /**
-     * @dataProvider someMethod()
-     */
+    #[\PHPUnit\Framework\Attributes\DataProvider('someMethod')]
     public function test(): void
     {
     }
 }

NamedArgumentForDataProviderRector

Change the array-index names to the argument name of the dataProvider

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public static function dataProviderArray(): array
     {
         return [
             [
-                'keyA' => true,
-                'keyB' => false,
+                'changeToKeyA' => true,
+                'changeToKeyB' => false,
             ]
         ];
     }

     #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderArray')]
     public function testFilter(bool $changeToKeyA, bool $changeToKeyB): void
     {
     }
 }

GetMockRector

Turns getMock*() methods to createMock()

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
-        $classMock = $this->getMock("Class");
+        $classMock = $this->createMock("Class");
     }
 }

SpecificAssertContainsWithoutIdentityRector

Change assertContains()/assertNotContains() with non-strict comparison to new specific alternatives

-final class SomeTest extends \PHPUnit\Framework\TestCase
+final class SomeTest extends TestCase
 {
     public function test()
     {
         $objects = [ new \stdClass(), new \stdClass(), new \stdClass() ];
-        $this->assertContains(new \stdClass(), $objects, 'message', false, false);
-        $this->assertNotContains(new \stdClass(), $objects, 'message', false, false);
+        $this->assertContainsEquals(new \stdClass(), $objects, 'message');
+        $this->assertNotContainsEquals(new \stdClass(), $objects, 'message');
     }
 }

ExplicitPhpErrorApiRector

Use explicit API for expecting PHP errors, warnings, and notices

 final class SomeTest extends \PHPUnit\Framework\TestCase
 {
     public function test()
     {
-        $this->expectException(\PHPUnit\Framework\TestCase\Deprecated::class);
-        $this->expectException(\PHPUnit\Framework\TestCase\Error::class);
-        $this->expectException(\PHPUnit\Framework\TestCase\Notice::class);
-        $this->expectException(\PHPUnit\Framework\TestCase\Warning::class);
+        $this->expectDeprecation();
+        $this->expectError();
+        $this->expectNotice();
+        $this->expectWarning();
     }
 }

ReplaceAtMethodWithDesiredMatcherRector

Replace at() method call with desired matcher

-$mock->expects($this->at(0))
+$mock->expects($this->never())
     ->method('foo')
     ->willReturn('1');
SETS:  Code Quality

TestListenerToHooksRector

Refactor "*TestListener.php" to particular "*Hook.php" files

 namespace App\Tests;

-use PHPUnit\Framework\TestListener;
-
-final class BeforeListHook implements TestListener
+final class BeforeListHook implements \PHPUnit\Runner\BeforeTestHook, \PHPUnit\Runner\AfterTestHook
 {
-    public function addError(Test $test, \Throwable $t, float $time): void
+    public function executeBeforeTest(Test $test): void
     {
-    }
-
-    public function addWarning(Test $test, Warning $e, float $time): void
-    {
-    }
-
-    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
-    {
-    }
-
-    public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
-    {
-    }
-
-    public function addRiskyTest(Test $test, \Throwable $t, float $time): void
-    {
-    }
-
-    public function addSkippedTest(Test $test, \Throwable $t, float $time): void
-    {
-    }
-
-    public function startTestSuite(TestSuite $suite): void
-    {
-    }
-
-    public function endTestSuite(TestSuite $suite): void
-    {
-    }
-
-    public function startTest(Test $test): void
-    {
         echo 'start test!';
     }

-    public function endTest(Test $test, float $time): void
+    public function executeAfterTest(Test $test, float $time): void
     {
         echo $time;
     }
 }

RemoveDataProviderTestPrefixRector

Data provider methods cannot start with "test" prefix

 class SomeClass extends PHPUnit\Framework\TestCase
 {
     /**
-     * @dataProvider testProvideData()
+     * @dataProvider provideData()
      */
     public function test()
     {
         $nothing = 5;
     }

-    public function testProvideData()
+    public function provideData()
     {
         return ['123'];
     }
 }

SpecificAssertContainsRector

Change assertContains()/assertNotContains() method to new string and iterable alternatives

 final class SomeTest extends \PHPUnit\Framework\TestCase
 {
     public function test()
     {
-        $this->assertContains('foo', 'foo bar');
-        $this->assertNotContains('foo', 'foo bar');
+        $this->assertStringContainsString('foo', 'foo bar');
+        $this->assertStringNotContainsString('foo', 'foo bar');
     }
 }

AssertEqualsParameterToSpecificMethodsTypeRector

Change assertEquals()/assertNotEquals() method parameters to new specific alternatives

 final class SomeTest extends \PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $value = 'value';
-        $this->assertEquals('string', $value, 'message', 5.0);
+        $this->assertEqualsWithDelta('string', $value, 5.0, 'message');

-        $this->assertEquals('string', $value, 'message', 0.0, 20);
+        $this->assertEquals('string', $value, 'message', 0.0);

-        $this->assertEquals('string', $value, 'message', 0.0, 10, true);
+        $this->assertEqualsCanonicalizing('string', $value, 'message');

-        $this->assertEquals('string', $value, 'message', 0.0, 10, false, true);
+        $this->assertEqualsIgnoringCase('string', $value, 'message');
     }
 }

SpecificAssertInternalTypeRector

Change assertInternalType()/assertNotInternalType() method to new specific alternatives

 final class SomeTest extends \PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $value = 'value';
-        $this->assertInternalType('string', $value);
-        $this->assertNotInternalType('array', $value);
+        $this->assertIsString($value);
+        $this->assertIsNotArray($value);
     }
 }

RemoveSetMethodsMethodCallRector

Remove "setMethods()" method as never used, move methods to "addMethods()" if non-existent or @method magic

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $someMock = $this->getMockBuilder(SomeClass::class)
-            ->setMethods(['run'])
             ->getMock();
     }
 }

PropertyExistsWithoutAssertRector

Replace removed assertClassHas*Attribute() with property_exists()

-$this->assertClassHasAttribute("Class", "property");
-$this->assertClassHasStaticAttribute("Class", "property");
+$this->assertTrue(property_exists("Class", "property"));
+$this->assertTrue(property_exists("Class", "property"));

WithConsecutiveRector

Refactor deprecated withConsecutive() to willReturnCallback() structure

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function run()
     {
-        $this->personServiceMock->expects($this->exactly(2))
+        $matcher = $this->exactly(2);
+
+        $this->personServiceMock->expects($matcher)
             ->method('prepare')
-            ->withConsecutive(
-                [1, 2],
-                [3, 4],
-            );
+            ->willReturnCallback(function (...$parameters) use ($matcher) {
+                if ($matcher->numberOfInvocations() === 1) {
+                    self::assertEquals([1, 2], $parameters);
+                }
+
+                if ($matcher->numberOfInvocations() === 2) {
+                    self::assertEquals([3, 4], $parameters),
+                };
+            });
     }
 }

PublicDataProviderClassMethodRector

Change data provider methods to public

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     /**
      * @dataProvider provideData()
      */
     public function test()
     {
     }

-    protected static function provideData()
+    public static function provideData()
     {
         yield [1];
     }
 }

AddProphecyTraitRector

Add Prophecy trait for method using $this->prophesize()

 use PHPUnit\Framework\TestCase;
+use Prophecy\PhpUnit\ProphecyTrait;

 final class ExampleTest extends TestCase
 {
+    use ProphecyTrait;
+
     public function testOne(): void
     {
         $prophecy = $this->prophesize(\AnInterface::class);
     }
 }

StaticDataProviderClassMethodRector

Change data provider methods to static

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     /**
      * @dataProvider provideData()
      */
     public function test()
     {
     }

-    public function provideData()
+    public static function provideData()
     {
         yield [1];
     }
 }

RemoveNamedArgsInDataProviderRector

Remove named arguments in data provider

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     /**
      * @dataProvider provideData()
      */
     public function test()
     {
     }

     public static function provideData()
     {
-        yield ['namedArg' => 100];
+        yield [100];
     }
 }

ParentTestClassConstructorRector

PHPUnit\Framework\TestCase requires a parent constructor call

 use PHPUnit\Framework\TestCase;

 final class SomeHelper extends TestCase
 {
+    public function __construct()
+    {
+        parent::__construct(static::class);
+    }
 }

GetMockBuilderGetMockToCreateMockRector

Remove getMockBuilder() to createMock()

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
-        $applicationMock = $this->getMockBuilder('SomeClass')
-           ->disableOriginalConstructor()
-           ->getMock();
+        $applicationMock = $this->createMock('SomeClass');
     }
 }

DelegateExceptionArgumentsRector

Takes setExpectedException() 2nd and next arguments to own methods in PHPUnit.

 use PHPUnit\Framework\TestCase;

 class SomeTest extends TestCase
 {
     public function test()
     {
-        $this->setExpectedException(SomeException::class, "Message", "CODE");
+        $this->setExpectedException(SomeException::class);
+        $this->expectExceptionMessage('Message');
+        $this->expectExceptionCode('CODE');
     }
 }

ExceptionAnnotationRector

Changes @expectedException annotations to expectException*()` methods

-/**
- * @expectedException Exception
- * @expectedExceptionMessage Message
- */
 public function test()
 {
+    $this->expectException('Exception');
+    $this->expectExceptionMessage('Message');
     // tested code
 }

AddDoesNotPerformAssertionToNonAssertingTestRector

Tests without assertion will have @doesNotPerformAssertion

 use PHPUnit\Framework\TestCase;

 class SomeClass extends TestCase
 {
+    /**
+     * @doesNotPerformAssertions
+     */
     public function test()
     {
         $nothing = 5;
     }
 }

AssertEqualsOrAssertSameFloatParameterToSpecificMethodsTypeRector

Change assertEquals()/assertSame() method using float on expected argument to new specific alternatives.

-$this->assertSame(10.20, $value);
-$this->assertEquals(10.200, $value);
+$this->assertEqualsWithDelta(10.20, $value, PHP_FLOAT_EPSILON);
+$this->assertEqualsWithDelta(10.200, $value, PHP_FLOAT_EPSILON);
SETS:  Code Quality

SimplerWithIsInstanceOfRector

Replaces use of with, callable and instance assert to simple isInstanceOf() method

-use PHPUnit\Framework\TestCase
+use PHPUnit\Framework\TestCase;

 final class SomeClass extends TestCase
 {
     public function test()
     {
         $someMock = $this->createMock(SomeClass::class)
             ->method('someMethod')
-            ->with($this->callable(function ($arg): bool {
-                return $arg instanceof SomeType;
-            }));
+            ->with($this->isInstanceOf(SomeType::class));
     }
 }
SETS:  Code Quality

AssertFalseStrposToContainsRector

Turns strpos/stripos comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertFalse(strpos($anything, "foo"), "message");
+$this->assertNotContains("foo", $anything, "message");
SETS:  Code Quality

RemoveExpectAnyFromMockRector

Remove expect($this->any()) from mocks as it has no added value

 use PHPUnit\Framework\TestCase;

 class SomeClass extends TestCase
 {
     public function test()
     {
         $translator = $this->getMock('SomeClass');
-        $translator->expects($this->any())
-            ->method('trans')
+        $translator->method('trans')
             ->willReturn('translated max {{ max }}!');
     }
 }
SETS:  Code Quality

AssertNotOperatorRector

Turns not-operator comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertTrue(!$foo, "message");
+$this->assertFalse($foo, "message");
SETS:  Code Quality

AssertCompareOnCountableWithMethodToAssertCountRector

Replaces use of assertSame and assertEquals on Countable objects with count method

-$this->assertSame(1, $countable->count());
+$this->assertCount(1, $countable);
SETS:  Code Quality

UseSpecificWithMethodRector

Changes ->with() to more specific method

 class SomeClass extends PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $translator = $this->createMock('SomeClass');

         $translator->expects($this->any())
             ->method('trans')
-            ->with($this->equalTo('old max {{ max }}!'));
+            ->with('old max {{ max }}!');
     }
 }
SETS:  Code Quality

AssertTrueFalseToSpecificMethodRector

Turns true/false comparisons to their method name alternatives in PHPUnit TestCase when possible

-$this->assertTrue(is_readable($readmeFile), "message");
+$this->assertIsReadable($readmeFile, "message");
SETS:  Code Quality

UseSpecificWillMethodRector

Changes $mock->will() call to more specific method

 class SomeClass extends PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $translator = $this->createMock('SomeClass');
         $translator->expects($this->any())
             ->method('trans')
-            ->will($this->returnValue('translated max {{ max }}!'));
+            ->willReturnValue('translated max {{ max }}!');
     }
 }
SETS:  Code Quality

FlipAssertRector

Turns accidentally flipped assert order to right one, with expected expr to left

 <?php

 namespace RectorPrefix202602;

 use PHPUnit\Framework\TestCase;
 class SomeTest extends TestCase
 {
     public function test()
     {
         $result = '...';
-        $this->assertSame($result, 'expected');
+        $this->assertSame('expected', $result);
     }
 }
 \class_alias('SomeTest', 'SomeTest', \false);
SETS:  Code Quality

AssertEqualsToSameRector

Turns assertEquals() into stricter assertSame() for scalar values in PHPUnit TestCase

-$this->assertEquals(2, $result);
+$this->assertSame(2, $result);
SETS:  Code Quality

AssertThatToDirectAssertRector

Change $this->assertThat($value, $this->*()) to direct $this->assert*() method

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
-        $this->assertThat($value, $this->isTrue());
+        $this->assertTrue($value);
     }
 }

AssertInstanceOfComparisonRector

Turns instanceof comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertTrue($foo instanceof Foo, "message");
+$this->assertInstanceOf("Foo", $foo, "message");
SETS:  Code Quality

MatchAssertSameExpectedTypeRector

Correct expected type in assertSame() method to match strict type of passed variable

 use PHPUnit\Framework\TestCase;

 class SomeTest extends TestCase
 {
     public function test()
     {
-        $this->assertSame('123', $this->getOrderId());
+        $this->assertSame(123, $this->getOrderId());
     }

     private function getOrderId(): int
     {
         return 123;
     }
 }
SETS:  Code Quality

SingleWithConsecutiveToWithRector

Change single-value withConsecutive() to with() call, willReturnOnConsecutiveCalls() to willReturn() call

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function run()
     {
         $this->personServiceMock->expects($this->exactly(3))
             ->method('prepare')
-            ->withConsecutive(
-                [1],
-            );
+            ->with([1]);
     }
 }
SETS:  Code Quality

AssertEmptyNullableObjectToAssertInstanceofRector

Change assertNotEmpty() and assertNotNull() on an object to more clear assertInstanceof()

 use PHPUnit\Framework\TestCase;

 class SomeClass extends TestCase
 {
     public function test()
     {
         $someObject = new stdClass();

-        $this->assertNotEmpty($someObject);
+        $this->assertInstanceof(stdClass::class, $someObject);
     }
 }
SETS:  Code Quality

AssertIssetToSpecificMethodRector

Turns assertTrue() + isset() comparisons to more precise assertArrayHasKey() method

-$this->assertTrue(isset($anything["foo"]), "message");
+$this->assertArrayHasKey("foo", $anything, "message");
SETS:  Code Quality

NarrowIdenticalWithConsecutiveRector

Narrow identical withConsecutive() and willReturnOnConsecutiveCalls() to single call

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function run()
     {
         $this->personServiceMock->expects($this->exactly(3))
             ->method('prepare')
-            ->withConsecutive(
-                [1],
-                [1],
-                [1],
-            )
-            ->willReturnOnConsecutiveCalls(
-                [2],
-                [2],
-                [2],
-            );
+            ->with([1])
+            ->willReturn([2]);
     }
 }
SETS:  Code Quality

AssertRegExpRector

Turns preg_match comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertSame(1, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertRegExp("/^Message for ".*"\.$/", $string, $message);
SETS:  Code Quality

StringCastAssertStringContainsStringRector

Cast 2nd argument in assertStringContainsString() to a string if not yet

 use PHPUnit\Framework\TestCase;

 class SomeTest extends TestCase
 {
     public function testSomething(?string $value)
     {
-        $this->assertStringContainsString('foo', $value);
+        $this->assertStringContainsString('foo', (string) $value);
     }
 }
SETS:  Code Quality

NarrowSingleWillReturnCallbackRector

Narrow single-value match willReturnCallback() to with() and willReturn() call

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function run()
     {
         $matcher = $this->exactly(1);

         $this->personServiceMock->expects($matcher)
-            ->willReturnCallback(function (...$parameters) use ($matcher) {
-                match ($matcher->getInvocationCount()) {
-                    1 => $this->assertSame([1], $parameters),
-                };
-            });
+            ->with(1, $parameters);
     }
 }
SETS:  Code Quality

AssertSameBoolNullToSpecificMethodRector

Turns same bool and null comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertSame(null, $anything);
+$this->assertNull($anything);
SETS:  Code Quality

WithCallbackIdenticalToStandaloneAssertsRector

Replaces identical compare in $this->callable() sole return to standalone PHPUnit asserts that show more detailed failure messages

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $this->createMock('SomeClass')
             ->expects($this->once())
             ->method('someMethod')
             ->with($this->callback(function (array $args): bool {
-                return count($args) === 2 && $args[0] === 'correct'
+                $this->assertCount(2, $args);
+                $this->assertSame('correct', $args[0]);
+
+                return true;
             }));
     }
 }
SETS:  Code Quality

MergeWithCallableAndWillReturnRector

Merge split mocking method ->with($this->callback(...)) and ->willReturn(expr) to single ->willReturnCallback() call

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $this->createMock('SomeClass')
             ->expects($this->once())
             ->method('someMethod')
-            ->with($this->callback(function (array $args): bool {
-                return true;
-            }))
-            ->willReturn(['some item']);
+            ->willReturnCallback(function (array $args): array {
+                return ['some item'];
+            });
     }
 }
SETS:  Code Quality

AssertComparisonToSpecificMethodRector

Turns comparison operations to their method name alternatives in PHPUnit TestCase

-$this->assertTrue($foo === $bar, "message");
+$this->assertSame($bar, $foo, "message");
SETS:  Code Quality

AssertSameTrueFalseToAssertTrueFalseRector

Change $this->assertSame(true, ...) to assertTrue()

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $value = (bool) mt_rand(0, 1);
-        $this->assertSame(true, $value);
+        $this->assertTrue($value);
     }
 }
SETS:  Code Quality

ScalarArgumentToExpectedParamTypeRector

Correct expected type in setter of tests, if param type is strictly defined

 use PHPUnit\Framework\TestCase;

 class SomeTest extends TestCase
 {
     public function test()
     {
         $someClass = new SomeClass();
-        $someClass->setPhone(12345);
+        $someClass->setPhone('12345');
     }
 }

 final class SomeClass
 {
     public function setPhone(string $phone)
     {
     }
 }
SETS:  Code Quality

AssertFuncCallToPHPUnitAssertRector

Turns assert() calls in tests to PHPUnit assert method alternative

 use PHPUnit\Framework\TestCase;

 class SomeClass extends TestCase
 {
     public function test()
     {
         $value = 1000;
-        assert($value === 1000, 'message');
+
+        $this->assertSame(1000, $value, "message")
     }
 }
SETS:  Code Quality

DirectInstanceOverMockArgRector

Use direct object instance over mock for specific objects in arg of PHPUnit tests

 use PHPUnit\Framework\TestCase;
 use Symfony\Component\HttpFoundation\Request;

 final class SomeTest extends TestCase
 {
     public function test()
     {
-        $this->someMethod($this->createMock(Request::class));
+        $this->someMethod(new Request());
     }

     private function someMethod($someClass)
     {
     }
 }
SETS:  Code Quality

DeclareStrictTypesTestsRector

Add declare(strict_types=1) to PHPUnit test class file

+declare(strict_types=1);
+
 use PHPUnit\Framework\TestCase;

 final class SomeTestWithoutStrict extends TestCase
 {
     public function test()
     {
     }
 }
SETS:  Code Quality

AssertArrayCastedObjectToAssertSameRector

Split object casted to array to assert public properties to standalone assert calls

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestClass
 {
     public function test()
     {
         $someObject = new SomeObject();

-        $this->assertSame([
-            'name' => 'John',
-            'surname' => 'Doe',
-        ], (array) $someObject));
+        $this->assertSame('John', $someObject->name);
+        $this->assertSame('Doe', $someObject->surname);
     }
 }
SETS:  Code Quality

ConfiguredMockEntityToSetterObjectRector

Change createConfigureMock() on Entity/Document object to direct new instance with setters

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestClass
 {
     public function test()
     {
-        $someObject = $this->createConfiguredMock(SomeObject::class, [
-            'name' => 'John',
-            'surname' => 'Doe',
-        ]);
+        $someObject = new SomeObject();
+        $someObject->setName('John');
+        $someObject->setSurname('Doe');
     }
 }

DecorateWillReturnMapWithExpectsMockRector

Decorate willReturnMap() calls with expects on the mock object if missing

 use PHPUnit\Framework\TestCase;
 use PHPUnit\Framework\MockObject\MockObject;

 final class SomeTest extends TestCase
 {
     private MockObject $someMock;

     protected function setUp(): void
     {
         $this->someMock = $this->createMock(SomeClass::class);

-        $this->someMock->method("someMethod")
+        $this->someMock->expects($this->exactly(2))
+            ->method("someMethod")
             ->willReturnMap([
                 ["arg1", "arg2", "result1"],
                 ["arg3", "arg4", "result2"],
             ]);
     }
 }
SETS:  Code Quality

SimplifyForeachInstanceOfRector

Simplify unnecessary foreach check of instances

-foreach ($foos as $foo) {
-    $this->assertInstanceOf(SplFileInfo::class, $foo);
-}
+$this->assertContainsOnlyInstancesOf(\SplFileInfo::class, $foos);
SETS:  Code Quality

PreferPHPUnitThisCallRector

Changes PHPUnit calls from self::assert*() to $this->assert*()

 use PHPUnit\Framework\TestCase;

 final class SomeClass extends TestCase
 {
     public function run()
     {
-        self::assertEquals('expected', $result);
+        $this->assertEquals('expected', $result);
     }
 }
SETS:  Code Quality

TypeWillReturnCallableArrowFunctionRector

Decorate callbacks and arrow functions in willReturnCallback() with known param/return types based on reflection method

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function testSomething()
     {
         $this->createMock(SomeClass::class)
             ->method('someMethod')
-            ->willReturnCallback(function ($arg) {
-                return $arg;
-            });
+            ->willReturnCallback(
+                function (string $arg): string {
+                    return $arg;
+                }
+            );
     }
 }

 final class SomeClass
 {
     public function someMethod(string $arg): string
     {
         return $arg . ' !';
     }
 }
SETS:  Code Quality

RemoveNeverUsedMockPropertyRector

Remove never used property mock, only to set expectations

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
-    private $mockProperty = null;
-
     protected function setUp(): void
     {
-        $this->mockProperty = $this->createMock(SomeClass::class);
-
-        $this->mockProperty->expects($this->once())
-            ->method('someMethod')
-            ->willReturn('someValue');
     }
 }
SETS:  Code Quality

SingleMockPropertyTypeRector

Make properties in tests with intersection mock object either object type or mock type

 use PHPUnit\Framework\TestCase;
 use PHPUnit\Framework\MockObject\MockObject;

 final class MockingEntity extends TestCase
 {
-    private SimpleObject|MockObject $someEntityMock;
+    private MockObject $someEntityMock;

     protected function setUp(): void
     {
         $this->someEntityMock = $this->createMock(SimpleObject::class);
     }
 }
SETS:  Code Quality

AddParamTypeFromDependsRector

Add param type declaration based on @depends test method return type

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test(): \stdClass
     {
         return new \stdClass();
     }

     /**
      * @depends test
      */
-    public function testAnother($someObject)
+    public function testAnother(\stdClass $someObject)
     {
     }
 }
SETS:  Code Quality

TestWithToDataProviderRector

Replace testWith annotation to data provider.

+public function dataProviderSum()
+{
+    return [
+        [0, 0, 0],
+        [0, 1, 1],
+        [1, 0, 1],
+        [1, 1, 3]
+    ];
+}
+
 /**
- * @testWith    [0, 0, 0]
- * @testWith    [0, 1, 1]
- * @testWith    [1, 0, 1]
- * @testWith    [1, 1, 3]
+ * @dataProvider dataProviderSum
  */
-public function testSum(int $a, int $b, int $expected)
+public function test(int $a, int $b, int $expected)
 {
     $this->assertSame($expected, $a + $b);
 }
SETS:  Code Quality

NarrowUnusedSetUpDefinedPropertyRector

Turn property used only in setUp() to variable

 use PHPUnit\Framework\TestCase;

 class SomeServiceTest extends TestCase
 {
-    private $someServiceMock;
-
     public function setUp(): void
     {
-        $this->someServiceMock = $this->createMock(SomeService::class);
+        $someServiceMock = $this->createMock(SomeService::class);
     }
 }
SETS:  Code Quality

YieldDataProviderRector

Turns array return to yield in data providers

 use PHPUnit\Framework\TestCase;

 final class SomeTest implements TestCase
 {
     public static function provideData()
     {
-        return [
-            ['some text']
-        ];
+        yield ['some text'];
     }
 }
SETS:  Code Quality

ConstructClassMethodToSetUpTestCaseRector

Change __construct() method in tests of PHPUnit\Framework\TestCase to setUp(), to prevent dangerous override

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     private $someValue;

-    public function __construct(?string $name = null, array $data = [], string $dataName = '')
+    protected function setUp()
     {
+        parent::setUp();
+
         $this->someValue = 1000;
-        parent::__construct($name, $data, $dataName);
     }
 }
SETS:  Code Quality

AddSeeTestAnnotationRector

Add @see annotation test of the class for faster jump to test. Make it FQN, so it stays in the annotation, not in the PHP source code.

+/**
+ * @see \SomeServiceTest
+ */
 class SomeService
 {
 }

 use PHPUnit\Framework\TestCase;

 class SomeServiceTest extends TestCase
 {
 }

PreferPHPUnitSelfCallRector

Changes PHPUnit calls from $this->assert*() to self::assert*()

 use PHPUnit\Framework\TestCase;

 final class SomeClass extends TestCase
 {
     public function run()
     {
-        $this->assertEquals('expected', $result);
+        self::assertEquals('expected', $result);
     }
 }

InlineStubPropertyToCreateStubMethodCallRector

Inline stub property only used to pass as new argument to a method call

 use PHPUnit\Framework\TestCase;
-use PHPUnit\Framework\MockObject\Stub;

 final class SomeTest extends TestCase
 {
-    private Stub $someStub;
-
-    protected function setUp(): void
-    {
-        $this->someStub = $this->createStub(SomeClass::class);
-    }
-
     public function testAnother()
     {
-        $anotherObject = new AnotherObject($this->someStub);
+        $anotherObject = new AnotherObject($this->createStub(SomeStub::class));
     }
 }
SETS:  Code Quality

SuffixMockObjectPropertyRector

Suffix mock object property names with "Mock" to clearly separate from real objects later on

 use PHPUnit\Framework\TestCase;
 use PHPUnit\Framework\MockObject\MockObject;

 final class MockingEntity extends TestCase
 {
-    private MockObject $simpleObject;
+    private MockObject $simpleObjectMock;

     protected function setUp(): void
     {
-        $this->simpleObject = $this->createMock(SimpleObject::class);
+        $this->simpleObjectMock = $this->createMock(SimpleObject::class);
     }

     public function test()
     {
-        $this->simpleObject->method('someMethod')->willReturn('someValue');
+        $this->simpleObjectMock->method('someMethod')->willReturn('someValue');
     }
 }

AddReturnTypeToDependedRector

Add return type declaration to a test method that returns type

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
-    public function test()
+    public function test(): \stdClass
     {
         $value = new \stdClass();

         return $value;
     }
 }
SETS:  Code Quality

AddKeysExistsAssertForKeyUseRector

Add assertArrayHasKey() call for array access with string key, that was not validated before

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $data = $this->getData();
+        $this->assertArrayHasKey('key', $data);
         $this->assertSame('result', $data['key']);
     }

     private function getData(): array
     {
         // return various data
         return [];
     }
 }

AddInstanceofAssertForNullableArgumentRector

Add explicit instance assert between above nullable object pass

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $someObject = $this->getSomeObject();
+        $this->assertInstanceOf(SomeClass::class, $someObject);

         $this->process($someObject);
     }

     private function getSomeObject(): ?SomeClass
     {
         if (mt_rand(0, 1)) {
             return new SomeClass();
         }

         return null;
     }

     private function process(SomeClass $someObject): void
     {
         // non-nullable use here
     }
 }
SETS:  Code Quality

NoSetupWithParentCallOverrideRector

Remove override attribute, if setUp()/tearDown() references parent call to improve readability

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
-    #[\Override]
     protected function setUp(): void
     {
         parent::setUp();

         $value = 100;
     }
 }
SETS:  Code Quality

EntityDocumentCreateMockToDirectNewRector

Move from entity mock, to direct use of class instance and setters

 use PHPUnit\Framework\TestCase;

 final class SomeFileTest extends TestCase
 {
     public function test()
     {
-        $tableMock = $this->createMock(Table::class);
-
-        $tableMock->expects(self::once())
-            ->method('isLocked')
-            ->willReturn(true);
+        $table = new Table();
+        $table->setLocked(true);
     }
 }
SETS:  Code Quality

AddInstanceofAssertForNullableInstanceRector

Add explicit instance assert between nullable object assign and method call on nullable object (spotted by PHPStan)

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $someObject = $this->getSomeObject();
+        $this->assertInstanceOf(SomeClass::class, $someObject);

         $value = $someObject->getSomeMethod();
     }

     private function getSomeObject(): ?SomeClass
     {
         if (mt_rand(0, 1)) {
             return new SomeClass();
         }

         return null;
     }
 }
SETS:  Code Quality

BareCreateMockAssignToDirectUseRector

Add explicit instance assert between above nullable object pass

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
-        $someObject = $this->createMock(SomeClass::class);
-        $this->process($someObject);
+        $this->process($this->createMock(SomeClass::class));
     }
-

     private function process(SomeClass $someObject): void
     {
     }
 }
SETS:  Code Quality

RemoveStandaloneCreateMockRector

Remove standalone method calls with no effect

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
-        $this->createMock('SomeClass');
     }
 }
SETS:  Code Quality

RemoveEmptyTestMethodRector

Remove empty test methods

 class SomeTest extends \PHPUnit\Framework\TestCase
 {
-    /**
-     * testGetTranslatedModelField method
-     *
-     * @return void
-     */
-    public function testGetTranslatedModelField()
-    {
-    }
 }
SETS:  Code Quality

ReplaceTestAnnotationWithPrefixedFunctionRector

Replace @test with prefixed function

 class SomeTest extends \PHPUnit\Framework\TestCase
 {
-    /**
-     * @test
-     */
-    public function onePlusOneShouldBeTwo()
+    public function testOnePlusOneShouldBeTwo()
     {
         $this->assertSame(2, 1+1);
     }
 }
SETS:  Code Quality

BehatPHPUnitAssertToWebmozartRector

Change PHPUnit assert in Behat context files to Webmozart Assert, as first require a TestCase instance

 use Behat\Behat\Context\Context;
-use PHPUnit\Framework\Assert;
+use Webmozart\Assert\Assert;

 final class SomeContext implements Context
 {
     public function someMethod()
     {
-        Assert::assertSame('expected', 'actual');
+        Assert::same('actual', 'expected');
     }
 }

DataProviderArrayItemsNewLinedRector

Change data provider in PHPUnit test case to newline per item

 use PHPUnit\Framework\TestCase;

 final class ImageBinaryTest extends TestCase
 {
     /**
      * @dataProvider provideData()
      */
     public function testGetBytesSize(string $content, int $number): void
     {
         // ...
     }

     public static function provideData(): array
     {
-        return [['content', 8], ['content123', 11]];
+        return [
+            ['content', 8],
+            ['content123', 11]
+        ];
     }
 }
SETS:  Code Quality

ReplaceTestFunctionPrefixWithAttributeRector

Replace @test with prefixed function

 class SomeTest extends \PHPUnit\Framework\TestCase
 {
-    public function testOnePlusOneShouldBeTwo()
+    #[Test]
+    public function onePlusOneShouldBeTwo()
     {
         $this->assertSame(2, 1+1);
     }
 }