Rector upgrades rules for PHPUnit

Overview

Rector Rules for PHPUnit

See available PHPUnit rules

Install

composer require rector/rector-phpunit

Use Sets

To add a set to your config, use Rector\PHPUnit\Set\PHPUnitSetList class and pick one of constants:

use Rector\PHPUnit\Set\PHPUnitSetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $containerConfigurator->import(PHPUnitSetList::PHPUNIT_90);
};
Comments
  • MigrateAtToConsecutiveExpectationsRector skips some cases

    MigrateAtToConsecutiveExpectationsRector skips some cases

    Add fixture for https://getrector.org/demo/1ec84192-9d46-65fc-947d-9f7ed7e29daf as discussed in https://github.com/rectorphp/rector/issues/6976#issuecomment-1027831779.

    opened by umpirsky 12
  • Referencing a class name in an exception message breaks refactoring to expectExceptionMessage

    Referencing a class name in an exception message breaks refactoring to expectExceptionMessage

    \Rector\PHPUnit\PhpDoc\PhpDocValueToNodeMapper::mapGenericTagValueNode is used for both the expected exception and the expected exception message when refactoring php doc tags into exception methods, which opportunistically tries to use class constants.

    If there happens to be :: in the exception message, then the exception message isn't treated as a string. Would it be possible to handle exception messages (and maybe regexps) as strings always? Otherwise invalid class constants can be written and generate invalid PHP.

    opened by camporter 11
  • Fatal error when using AbstractRectorTestCase in PHP8

    Fatal error when using AbstractRectorTestCase in PHP8

    Rector 130b634b5e348554c3349ed3b3f52fa3d08bfb6e PHPUnit 8.5

    PHP Fatal error:  Declaration of Rector\Testing\PHPUnit\PlatformAgnosticAssertions::assertStringEqualsFile($expectedFile, $actualString, $message = ''): void must be compatible with PHPUnit\Framework\Assert::assertStringEqualsFile(string $expectedFile, string $actualString, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void in /var/www/html/vendor/rector/rector/packages/Testing/PHPUnit/AbstractTestCase.php on line 41
    
    opened by leighman 8
  • Rule suggestion: Using rector to fix prophecy typehints

    Rule suggestion: Using rector to fix prophecy typehints

    We have a big codebase in @sulu and lots of our testcases are not really analyzeable by phpstan as there are lot of false typehints for mocks (we have a very very big baseline). We are using prophecy for mocking. And there are different false typehints in our codebase:

    Variant A (class but didnt define mock):

    class MyClassTest extends TestCase {
        /**
         * @var MyClass
         */
        private $my;
    
        public function setUp(): void
        {
             $this->my = $this->prophesize(MyClass::class);
        }
    }
    

    Variant B (mock but didnt define class):

    class MyClassTest extends TestCase {
        /**
         * @var ObjectProphecy
         */
        private $my;
    
        public function setUp(): void
        {
             $this->my = $this->prophesize(MyClass::class);
        }
    }
    

    Variant C (mock or class (is still false but works sometimes)):

    class MyClassTest extends TestCase {
        /**
         * @var ObjectProphecy|MyClass
         */
        private $my;
    
        public function setUp(): void
        {
             $this->my = $this->prophesize(MyClass::class);
        }
    }
    

    Variant D (nothing defined):

    class MyClassTest extends TestCase {
        private $my;
    
        public function setUp(): void
        {
             $this->my = $this->prophesize(MyClass::class);
        }
    }
    

    Expected would be ObjectProphecy Generic with the class:

    class MyClassTest extends TestCase {
        /**
         * @var ObjectProphecy<MyClass>
         */
        private $my;
    
        public function setUp(): void
        {
             $this->my = $this->prophesize(MyClass::class);
        }
    }
    

    So I asked myself if rector could be used to provide a rule to analyze all $this->prophesize calls and set the correct type for this classes. Think it would be a great rule which could be shipped with rector via a CodeQuality ruleset. Any hints are welcome how to achieve this :)

    opened by alexander-schranz 6
  • AssertEqualsToSameRector converts even if testing arrays contain objects

    AssertEqualsToSameRector converts even if testing arrays contain objects

    Given the following code:

    $expected = ['date' => new DateTimeImmutable('2022-10-31 12:32:33')];
    $date = new DateTimeImmutable('2022-10-31 12:32:33');
    $actual = compact('date');
    
    self::assertEquals($expected, $actual);
    

    The new version of the rule will change the assertion to assertSame but this would lead to an error given this will check the two arrays contain exactly the same object.

    opened by vitxd 5
  • RemoveDataProviderTestPrefixRector does not take class inheritance into account

    RemoveDataProviderTestPrefixRector does not take class inheritance into account

    I noticed a problem with how RemoveDataProviderTestPrefixRector that I think is related to how I'm using inheritance in tests for a project of mine.

    I have a base class for tests with a test method that uses an illegally named data provider:

     /**
       * blah blah blah
       *
       * @dataProvider testExceptionsProvider
       */
      public function testExceptions($filename, $message) {
    

    The rector rule correctly updates the annotation to read:

      /**
       * blah blah blah
       *
       * @dataProvider exceptionsProvider
       */
      public function testExceptions($filename, $message) {
    

    However, the annotation in the base class is the only place that the data provider name is changed.

    The rector rule seems to be getting "confused" because of how I'm relying on inheritance in these test classes. Specifically:

    1. testExceptions() is only declared in the base class.
    2. testExceptionsProvider() is not declared in the base test class. It is declared in each of the test classes that extend the base class.

    For the record, I am seeing this on a Drupal project that I maintain: https://www.drupal.org/project/crossword/issues/3286830

    Thanks!

    opened by danflanagan8 5
  • [Feature] Add TestClassNameResolverInterface to allow custom implementations

    [Feature] Add TestClassNameResolverInterface to allow custom implementations

    PR for https://github.com/rectorphp/rector-phpunit/issues/51

    I have tested this locally by applying a patch to the rector's vendor directory, and then in rector.php

        $services->set(
            \Rector\PHPUnit\Naming\TestClassNameResolverInterface::class,
            \Utils\Rector\Rector\PHPUnit\Naming\CustomTestClassNameResolver::class
        );
    
    opened by dorrogeray 5
  • Rector converted assertContains(string, array) to assertStringContainsString(string, array)

    Rector converted assertContains(string, array) to assertStringContainsString(string, array)

    Not sure how that could happen.

    Concrete code:

    $columns = array_map(function ($row) {
         return $row['column_name'];
    }, $connection->fetchAll(sprintf('SHOW COLUMNS IN %s', $connection->quoteIdentifier('updatedDisplayName'))));
    
    $this->assertContains('add_test_column', $columns);
    
    // fetchAll(): array - it's a custom ODBC driver implementation. My only idea was that somehow it thought that it could be false as well 
    
    opened by tomasfejfar 4
  • PHP Fatal error in Rector 0.11 when import PHPUnitSetList::PHPUNIT_CODE_QUALITY

    PHP Fatal error in Rector 0.11 when import PHPUnitSetList::PHPUNIT_CODE_QUALITY

    PHP Fatal error:  Uncaught Error: Class "RectorPrefix20210513\Nette\Loaders\RobotLoader" not found in /home/runner/work/coding-standard/coding-standard/vendor/rector/rector/vendor/rector/rector-phpunit/src/RobotLoader/RobotLoaderFactory.php:14
    
    opened by zingimmick 4
  • Add a rector turning data providers into static methods

    Add a rector turning data providers into static methods

    PHPUnit will deprecate using non-static methods as data providers: https://github.com/sebastianbergmann/phpunit/commit/9caafe2d49b33a21f87db248a8ad6ca7c7bdac09

    It would be great to have a rector that automatically turns data provider methods (i.e. methods referenced in @dataProvider annotations or the equivalent attribute) into static methods (the extra safety would do that only if they are not called or overridden somewhere else)

    opened by stof 3
  • [Set] Annotation to attribute for PHPUnit 10

    [Set] Annotation to attribute for PHPUnit 10

    PHPUnit will support attributes in version 10.
    It would be cool to have day 1 support. ref issue: https://github.com/rectorphp/rector-phpunit/issues/69

    This is work in progress because currently AnnotationToAttribute:

    1. do not support syntax like: @dataProvider data or @group api (those are probably most common)
    2. are not aware if the annotation is attached to method or class

    Probably some new class like PHPUnitAnnotationToAttribute is needed. @TomasVotruba Any feedback is welcome.

    opened by wkania 3
  • [PHPUnit 10] Abstract test classes cannot use *Test suffix

    [PHPUnit 10] Abstract test classes cannot use *Test suffix

    Since PHPUnit 10, it is not allowed to name abstract test classes with *Test suffix, for example: abstract class MyBaseTest should be renamed to abstract class MyBaseTestCase, etc. Many existing projects use this naming convention and need refactoring.

    Please note that base *Test and target *TestCase suffixes should be customizable (users may choose different suffixes in phpunit.xml using <directory suffix="Test.php">).

    For reference: https://github.com/sebastianbergmann/phpunit/issues/4979

    opened by IonBazan 1
  • Use AddVoidReturnTypeWhereNoReturnRector on classes extending TestCase

    Use AddVoidReturnTypeWhereNoReturnRector on classes extending TestCase

    There exists a rector rule called AddVoidReturnTypeWhereNoReturnRector. It would be nice if we could add to rector-phpunit to the PHPUNIT_CODE_QUALITY a rule to add this to all classes extending from PHPUnits TestCase class or any other class extending from PHPUnit TestClass. The AddVoidReturnTypeWhereNoReturnRector is currently final.

    What do you think the best way is to implement this. Currently we can not extend from AddVoidReturnTypeWhereNoReturnRector to achieve this simple here. Another option could be that we extend the AddVoidReturnTypeWhereNoReturnRector Rule in rector itself to filter by a class / interface and apply the rule only for that kind of classes, not sure if that kind of things make sense as a "General" Rector feature. That all rules could be limited to specific classes extending or implementing from a specific interface?

    opened by alexander-schranz 0
  • Thoughts on removing TestListener to TestHook rule?

    Thoughts on removing TestListener to TestHook rule?

    There is a rule provided in phpunit90 rule set that converts TestListener usages to TestHook usages. This was done because phpunit deprecated TestListener and provided somewhat similar functionality under their TestHook system. This has a couple gotchas where I think maybe removing this from the rule set may be a good idea?

    First is the TestListener service provides wildly different functionality to the TestHook system, For example TestListener provides the actual test object whereas the TestHook only provides a string representation. Unfortunately this means that there is a large part of functionality available that a simple method signature change can't ever address.

    I think the more important issue though is that TestHook is not a system they recommend to use nor is it actually staying long term, a new event system is under development for phpunit 10. You can see some of the discussion around that here https://github.com/sebastianbergmann/phpunit/issues/3390.

    The main reason I suggest this change is that its a potentially breaking change rule since the interface isn't at all the same but its also not even a system that will be in use going forward. I can make a PR to do this but wanted to discuss first what your thoughts were on this?

    Just for reference the rule I"m talking about. https://github.com/rectorphp/rector-phpunit/blob/main/config/sets/phpunit90.php#L13

    opened by ccovey 2
  • GetMockBuilderGetMockToCreateMockRector breaks test code

    GetMockBuilderGetMockToCreateMockRector breaks test code

    1) tests/system/Email/EmailTest.php:138
    
        ---------- begin diff ----------
    @@ @@
    
         public function testDestructDoesNotThrowException()
         {
    -        $email = $this->getMockBuilder(Email::class)
    -            ->disableOriginalConstructor()
    -            ->onlyMethods(['sendCommand'])
    -            ->getMock();
    +        $email = $this->createMock(Email::class);
             $email->method('sendCommand')
                 ->willThrowException(new ErrorException('SMTP Error.'));
        ----------- end diff -----------
    
    Applied rules:
     * GetMockBuilderGetMockToCreateMockRector (https://github.com/lmc-eu/steward/pull/187/files#diff-c7e8c65e59b8b4ff8b54325814d4ba55L80)
    

    But when I run the test, I got the error:

    $ vendor/bin/phpunit tests/system/Email/EmailTest.php
    PHPUnit 9.5.21 #StandWithUkraine
    
    Runtime:       PHP 8.0.20
    Configuration: .../CodeIgniter4/phpunit.xml
    
    ........E                                                           9 / 9 (100%)E                                                           9 / 9 (100%)
    
    Time: 00:00.358, Memory: 14.00 MB
    
    There was 1 error:
    
    1) CodeIgniter\Email\EmailTest::testDestructDoesNotThrowException
    PHPUnit\Framework\MockObject\MethodNameNotConfiguredException: Method name is not configured
    
    ERRORS!
    Tests: 9, Assertions: 20, Errors: 1.
    
    opened by kenjis 4
Qase-phpunit - Qase TMS PHPUnit reporter.

Qase TMS PHPUnit reporter Publish results simple and easy. How to integrate composer require qase/phpunit-reporter Example of usage The PHPUnit report

Qase TMS 6 Nov 24, 2022
Mockery - Designed as a drop in alternative to PHPUnit's phpunit-mock-objects library

Mockery Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its c

Mockery 10.3k Jan 1, 2023
PHPStan PHPUnit extensions and rules

PHPStan PHPUnit extensions and rules PHPStan PHPUnit This extension provides following features: createMock(), getMockForAbstractClass() and getMockFr

PHPStan 359 Dec 28, 2022
The most powerful and flexible mocking framework for PHPUnit / Codeception.

AspectMock AspectMock is not an ordinary PHP mocking framework. With the power of Aspect Oriented programming and the awesome Go-AOP library, AspectMo

Codeception Testing Framework 777 Dec 12, 2022
:computer: Parallel testing for PHPUnit

ParaTest The objective of ParaTest is to support parallel testing in PHPUnit. Provided you have well-written PHPUnit tests, you can drop paratest in y

null 2k Dec 31, 2022
vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with any unit test framework, like PHPUnit or SimpleTest.

vfsStream vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with

null 1.4k Dec 23, 2022
Add mocking capabilities to Pest or PHPUnit

This repository contains the Pest Plugin Mock. The Mocking API can be used in regular PHPUnit projects. For that, you just have to run the following c

PEST 16 Dec 3, 2022
A sample RESTful API in Laravel with PHPunit test.

Laravel PHP Framework URL | URI | Action |

Fasil 9 Jul 11, 2020
PHPUnit Application Architecture Test

PHPUnit Application Architecture Test Idea: write architecture tests as well as feature and unit tests Installation Install via composer composer requ

null 19 Dec 11, 2022
PHPUnit to Pest Converter

PestConverter PestConverter is a PHP library for converting PHPUnit tests to Pest tests. Before use Before using this converter, make sure your files

null 10 Nov 21, 2022
Allows the running of PHPUnit within ExpressionEngine

EE Unit Tests EE Unit Tests is an Add-on for ExpressionEngine that allows developers to execute unit tests from the Command Line. EE Unit Tests uses P

Eric Lamb 6 Jan 14, 2022
PHP libraries that makes Selenium WebDriver + PHPUnit functional testing easy and robust

Steward: easy and robust testing with Selenium WebDriver + PHPUnit Steward is a set of libraries made to simplify writing and running robust functiona

LMC s.r.o. 219 Dec 17, 2022
PHPUnit extension for database interaction testing.

This extension is no longer maintained DbUnit PHPUnit extension for database interaction testing. Installation Composer If you use Composer to manage

Sebastian Bergmann 224 Aug 20, 2022
Mock implementation of the Translation package, for testing with PHPUnit

PoP Translation - Mock Mock implementation of the Translation package, for testing with PHPUnit Install Via Composer composer require getpop/translati

PoP 1 Jan 13, 2022
Magento PHPUnit Integration

Magento PHPUnit Integration Magento is a quite complex platform without built in unit test suite, so the code is not oriented on running tests over it

EcomDev B.V. 303 Dec 18, 2022
The objective of ParaTest is to support parallel testing in PHPUnit

The objective of ParaTest is to support parallel testing in PHPUnit. Provided you have well-written PHPUnit tests, you can drop paratest in your project and start using it with no additional bootstrap or configurations!

null 2k Dec 31, 2022
Report high memory usage PHPUnit tests: Managed by opg-org-infra & Terraform

phpunit-memory-usage Report high memory usage PHPUnit tests: Managed by opg-org-infra & Terraform Configuration Add into the phpunit.xml extensions se

Ministry of Justice 2 Aug 4, 2022
Satisfy the Type APIs for the WordPress schema when running PHPUnit tests

Satisfy the Type APIs for the WordPress schema when running PHPUnit tests

GraphQL API 1 Apr 12, 2022