75d1dca2ef
Don't get type from PropertyFetch for not natively typed properties (#3327)
28 KiB
48 Rules Overview
AddDoesNotPerformAssertionToNonAssertingTestRector
Tests without assertion will have @doesNotPerformAssertion
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
{
+ /**
+ * @doesNotPerformAssertions
+ */
public function test()
{
$nothing = 5;
}
}
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);
}
}
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
{
}
AnnotationWithValueToAttributeRector
Change annotations with value to attribute
🔧 configure it!
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\PHPUnit\Rector\Class_\AnnotationWithValueToAttributeRector;
use Rector\PHPUnit\ValueObject\AnnotationWithValueToAttribute;
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->ruleWithConfiguration(AnnotationWithValueToAttributeRector::class, [
new AnnotationWithValueToAttribute('backupGlobals', 'PHPUnit\Framework\Attributes\BackupGlobals', [
true,
false,
]),
]);
};
↓
use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\BackupGlobals;
-/**
- * @backupGlobals enabled
- */
+#[BackupGlobals(true)]
final class SomeTest extends TestCase
{
}
ArrayArgumentToDataProviderRector
Move array argument from tests into data provider [configurable]
🔧 configure it!
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\PHPUnit\Rector\Class_\ArrayArgumentToDataProviderRector;
use Rector\PHPUnit\ValueObject\ArrayArgumentToDataProvider;
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->ruleWithConfiguration(ArrayArgumentToDataProviderRector::class, [
ArrayArgumentToDataProviderRector::ARRAY_ARGUMENTS_TO_DATA_PROVIDERS => [
new ArrayArgumentToDataProvider('PHPUnit\Framework\TestCase', 'doTestMultiple', 'doTestSingle', 'number'),
],
]);
};
↓
use PHPUnit\Framework\TestCase;
class SomeServiceTest extends TestCase
{
- public function test()
+ /**
+ * @dataProvider provideData()
+ */
+ public function test(int $number)
{
- $this->doTestMultiple([1, 2, 3]);
+ $this->doTestSingle($number);
+ }
+
+ public function provideData(): \Iterator
+ {
+ yield [1];
+ yield [2];
+ yield [3];
}
}
AssertCompareToSpecificMethodRector
Turns vague php-only method in PHPUnit TestCase to more specific
-$this->assertSame(10, count($anything), "message");
+$this->assertCount(10, $anything, "message");
-$this->assertNotEquals(get_class($value), SomeInstance::class);
+$this->assertNotInstanceOf(SomeInstance::class, $value);
AssertComparisonToSpecificMethodRector
Turns comparison operations to their method name alternatives in PHPUnit TestCase
-$this->assertTrue($foo === $bar, "message");
+$this->assertSame($bar, $foo, "message");
-$this->assertFalse($foo >= $bar, "message");
+$this->assertLessThanOrEqual($bar, $foo, "message");
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');
}
}
AssertEqualsToSameRector
Turns assertEquals()
into stricter assertSame()
for scalar values in PHPUnit TestCase
-$this->assertEquals(2, $result);
+$this->assertSame(2, $result);
AssertFalseStrposToContainsRector
Turns strpos
/stripos
comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertFalse(strpos($anything, "foo"), "message");
+$this->assertNotContains("foo", $anything, "message");
AssertInstanceOfComparisonRector
Turns instanceof comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertTrue($foo instanceof Foo, "message");
+$this->assertInstanceOf("Foo", $foo, "message");
-$this->assertFalse($foo instanceof Foo, "message");
+$this->assertNotInstanceOf("Foo", $foo, "message");
AssertIssetToSpecificMethodRector
Turns isset comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertTrue(isset($anything->foo));
+$this->assertObjectHasAttribute("foo", $anything);
-$this->assertFalse(isset($anything["foo"]), "message");
+$this->assertArrayNotHasKey("foo", $anything, "message");
AssertNotOperatorRector
Turns not-operator comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertTrue(!$foo, "message");
+$this->assertFalse($foo, "message");
-$this->assertFalse(!$foo, "message");
+$this->assertTrue($foo, "message");
AssertPropertyExistsRector
Turns property_exists
comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertFalse(property_exists(new Class, "property"));
-$this->assertTrue(property_exists(new Class, "property"));
+$this->assertClassHasAttribute("property", "Class");
+$this->assertClassNotHasAttribute("property", "Class");
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);
-$this->assertEquals(false, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertNotRegExp("/^Message for ".*"\.$/", $string, $message);
AssertResourceToClosedResourceRector
Turns assertIsNotResource()
into stricter assertIsClosedResource()
for resource values in PHPUnit TestCase
-$this->assertIsNotResource($aResource, "message");
+$this->assertIsClosedResource($aResource, "message");
AssertSameBoolNullToSpecificMethodRector
Turns same bool and null comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertSame(null, $anything);
+$this->assertNull($anything);
-$this->assertNotSame(false, $anything);
+$this->assertNotFalse($anything);
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);
}
}
AssertTrueFalseInternalTypeToSpecificMethodRector
Turns true/false with internal type comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertTrue(is_{internal_type}($anything), "message");
+$this->assertInternalType({internal_type}, $anything, "message");
-$this->assertFalse(is_{internal_type}($anything), "message");
+$this->assertNotInternalType({internal_type}, $anything, "message");
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");
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);
}
}
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)]
final class SomeTest extends TestCase
{
- /**
- * @covers ::someFunction
- */
+ #[CoversFunction('someFunction')]
public function test()
{
}
}
CreateMockToAnonymousClassRector
Change $this->createMock()
with methods to direct anonymous class
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
public function test()
{
- $someMockObject = $this->createMock(SomeClass::class);
-
- $someMockObject->method('someMethod')
- ->willReturn(100);
+ $someMockObject = new class extends SomeClass {
+ public function someMethod()
+ {
+ return 100;
+ }
+ };
}
}
CreateMockToCreateStubRector
Replaces createMock()
with createStub()
when relevant
use PHPUnit\Framework\TestCase
class MyTest extends TestCase
{
public function testItBehavesAsExpected(): void
{
- $stub = $this->createMock(\Exception::class);
+ $stub = $this->createStub(\Exception::class);
$stub->method('getMessage')
->willReturn('a message');
$mock = $this->createMock(\Exception::class);
$mock->expects($this->once())
->method('getMessage')
->willReturn('a message');
self::assertSame('a message', $stub->getMessage());
self::assertSame('a message', $mock->getMessage());
}
}
DataProviderAnnotationToAttributeRector
Change dataProvider annotations to attribute
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
- /**
- * @dataProvider someMethod()
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('test')]
public function test(): void
{
}
}
DelegateExceptionArgumentsRector
Takes setExpectedException()
2nd and next arguments to own methods in PHPUnit.
-$this->setExpectedException(SomeException::class, "Message", "CODE");
+$this->setExpectedException(SomeException::class);
+$this->expectExceptionMessage('Message');
+$this->expectExceptionCode('CODE');
DependsAnnotationWithValueToAttributeRector
Change depends annotations with value to attribute
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
public function testOne() {}
public function testTwo() {}
- /**
- * @depends testOne
- * @depends testTwo
- */
+ #[\PHPUnit\Framework\Attributes\Depends('testOne')]
+ #[\PHPUnit\Framework\Attributes\Depends('testTwo')]
public function testThree(): void
{
}
}
ExceptionAnnotationRector
Changes ``@expectedExceptionannotations to
expectException*()` methods
-/**
- * @expectedException Exception
- * @expectedExceptionMessage Message
- */
public function test()
{
+ $this->expectException('Exception');
+ $this->expectExceptionMessage('Message');
// tested code
}
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();
}
}
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');
}
}
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");
}
}
ProphecyPHPDocRector
Add correct @var
to ObjectProphecy instances based on $this->prophesize()
call.
class HelloTest extends TestCase
{
/**
- * @var SomeClass
+ * @var ObjectProphecy<SomeClass>
*/
private $propesizedObject;
public function setUp(): void
{
$this->propesizedObject = $this->prophesize(SomeClass::class);
}
}
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'];
}
}
RemoveEmptyTestMethodRector
Remove empty test methods
class SomeTest extends \PHPUnit\Framework\TestCase
{
- /**
- * testGetTranslatedModelField method
- *
- * @return void
- */
- public function testGetTranslatedModelField()
- {
- }
}
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 }}!');
}
}
RemoveSetMethodsMethodCallRector
Remove "setMethods()"
method as never used
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
public function test()
{
$someMock = $this->getMockBuilder(SomeClass::class)
- ->setMethods(['run'])
->getMock();
}
}
RemoveTestSuffixFromAbstractTestClassesRector
Rename abstract test class suffix from "*Test" to "*TestCase"
-// tests/AbstractTest.php
+// tests/AbstractTestCase.php
use PHPUnit\Framework\TestCase;
-abstract class AbstractTest extends TestCase
+abstract class AbstractTestCase extends TestCase
{
}
ReplaceAssertArraySubsetWithDmsPolyfillRector
Change assertArraySubset()
to static call of DMS\PHPUnitExtensions\ArraySubset\Assert
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
{
public function test()
{
- self::assertArraySubset(['bar' => 0], ['bar' => '0'], true);
+ \DMS\PHPUnitExtensions\ArraySubset\Assert::assertArraySubset(['bar' => 0], ['bar' => '0'], true);
- $this->assertArraySubset(['bar' => 0], ['bar' => '0'], true);
+ \DMS\PHPUnitExtensions\ArraySubset\Assert::assertArraySubset(['bar' => 0], ['bar' => '0'], true);
}
}
ReplaceTestAnnotationWithPrefixedFunctionRector
Replace @test
with prefixed function
class SomeTest extends \PHPUnit\Framework\TestCase
{
- /**
- * @test
- */
- public function onePlusOneShouldBeTwo()
+ public function testOnePlusOneShouldBeTwo()
{
$this->assertSame(2, 1+1);
}
}
SimplifyForeachInstanceOfRector
Simplify unnecessary foreach check of instances
-foreach ($foos as $foo) {
- $this->assertInstanceOf(SplFileInfo::class, $foo);
-}
+$this->assertContainsOnlyInstancesOf(\SplFileInfo::class, $foos);
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');
}
}
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');
}
}
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);
}
}
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];
}
}
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;
}
}
TryCatchToExpectExceptionRector
Turns try/catch to expectException()
call
-try {
- $someService->run();
-} catch (Throwable $exception) {
- $this->assertInstanceOf(RuntimeException::class, $e);
- $this->assertContains('There was an error executing the following script', $e->getMessage());
-}
+$this->expectException(RuntimeException::class);
+$this->expectExceptionMessage('There was an error executing the following script');
+$someService->run();
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 }}!');
}
}
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 }}!');
}
}