sebastianbergmann / phpunit

The PHP Unit Testing framework.
https://phpunit.de/
BSD 3-Clause "New" or "Revised" License
19.69k stars 2.2k forks source link

Method * may not return value of type class@anonymous, its declared return type is ** #5286

Closed NickSun closed 1 year ago

NickSun commented 1 year ago
Q A
PHPUnit version 10.0.16
PHP version 8.2.3
Installation Method Composer
amphp/amp                            v2.6.2           A non-blocking concurrency framework for PHP applications.
amphp/byte-stream                    v1.8.1           A stream abstraction to make working with non-blocking I/O simple.
amphp/parallel                       v1.4.2           Parallel processing component for Amp.
amphp/parallel-functions             v1.1.0           Parallel processing made simple.
amphp/parser                         v1.1.0           A generator parser to make streaming parsers simple.
amphp/process                        v1.1.4           Asynchronous process manager.
amphp/serialization                  v1.0.0           Serialization tools for IPC and data storage in PHP.
amphp/sync                           v1.4.2           Mutex, Semaphore, and other synchronization tools for Amp.
barryvdh/laravel-ide-helper          v2.13.0          Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.
barryvdh/reflection-docblock         v2.1.0          
brick/math                           0.11.0           Arbitrary-precision arithmetic library
composer/class-map-generator         1.0.0            Utilities to scan PHP code and generate class maps.
composer/pcre                        3.1.0            PCRE wrapping library that offers type-safe preg_* replacements.
composer/semver                      3.3.2            Semver library that offers utilities, version constraint parsing and validation.
composer/xdebug-handler              3.0.3            Restarts a process without Xdebug.
dflydev/dot-access-data              v3.0.2           Given a deep data structure, access data by dot notation.
doctrine/annotations                 2.0.1            Docblock Annotations Parser
doctrine/cache                       2.2.0            PHP Doctrine Cache library is a popular cache implementation that supports many different drivers such as redis, memcache, apc, mongodb and others.
doctrine/collections                 2.1.2            PHP Doctrine Collections library that adds additional functionality on top of PHP arrays.
doctrine/dbal                        3.6.1            Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.
doctrine/deprecations                v1.0.0           A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.
doctrine/event-manager               2.0.0            The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.
doctrine/inflector                   2.0.6            PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.
doctrine/lexer                       3.0.0            PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.
dragonmantank/cron-expression        v3.3.2           CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due
egulias/email-validator              4.0.1            A library for validating emails against several RFCs
fakerphp/faker                       v1.21.0          Faker is a PHP library that generates fake data for you.
friendsofphp/php-cs-fixer            v3.15.1          A tool to automatically fix PHP code style
fruitcake/php-cors                   v1.2.0           Cross-origin resource sharing library for the Symfony HttpFoundation
gitonomy/gitlib                      v1.3.7           Library for accessing git
graham-campbell/result-type          v1.1.1           An Implementation Of The Result Type
guzzlehttp/uri-template              v1.0.1           A polyfill class for uri_template of PHP
laravel/framework                    v10.4.1          The Laravel Framework.
laravel/serializable-closure         v1.3.0           Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.
league/commonmark                    2.3.9            Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and GitHub-Flavored Markdown (GFM)
league/config                        v1.2.0           Define configuration arrays with strict schemas and access values with dot notation
league/flysystem                     3.12.3           File storage abstraction for PHP
league/fractal                       0.20.1           Handle the output of complex data structures ready for API output.
league/mime-type-detection           1.11.0           Mime-type detection for Flysystem
matanyadaev/laravel-eloquent-spatial 3.1.2            Spatial library for Laravel
monolog/monolog                      3.3.1            Sends your logs to files, sockets, inboxes, databases and various web services
myclabs/deep-copy                    1.11.1           Create deep copies (clones) of your objects
nesbot/carbon                        2.66.0           An API extension for DateTime that supports 281 different languages.
nette/schema                         v1.2.3           šŸ“ Nette Schema: validating data structures against a given Schema.
nette/utils                          v4.0.0           šŸ›   Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generatin...
nikic/php-parser                     v4.15.4          A PHP parser written in PHP
nunomaduro/termwind                  v1.15.1          Its like Tailwind CSS, but for the console.
ondram/ci-detector                   4.1.0            Detect continuous integration environment and provide unified access to properties of current build
phar-io/manifest                     2.0.3            Component for reading phar.io manifest information from a PHP Archive (PHAR)
phar-io/version                      3.2.1            Library for handling version information and constraints
phayes/geophp                        1.2              GeoPHP is a open-source native PHP library for doing geometry operations. It is written entirely in PHP and can therefore run on shared hosts. It can read and write...
phpdocumentor/reflection-common      2.2.0            Common reflection classes used by phpdocumentor to reflect the code structure
phpdocumentor/type-resolver          1.7.0            A PSR-5 based resolver of Class names, Types and Structural Element Names
phpoption/phpoption                  1.9.1            Option Type for PHP
phpro/grumphp                        v1.15.0          A composer plugin that enables source code quality checks.
phpstan/phpdoc-parser                1.16.1           PHPDoc parser with support for nullable, intersection and generic types
phpunit/php-code-coverage            10.0.2           Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator            4.0.1            FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-invoker                  4.0.0            Invoke callables with a timeout
phpunit/php-text-template            3.0.0            Simple template engine.
phpunit/php-timer                    6.0.0            Utility class for timing
phpunit/phpunit                      10.0.16          The PHP Unit Testing framework.
psr/cache                            3.0.0            Common interface for caching libraries
psr/container                        2.0.2            Common Container Interface (PHP FIG PSR-11)
psr/event-dispatcher                 1.0.0            Standard interfaces for event handling.
psr/log                              3.0.0            Common interface for logging libraries
psr/simple-cache                     3.0.0            Common interfaces for simple caching
ramsey/collection                    2.0.0            A PHP library for representing and manipulating collections.
ramsey/uuid                          4.x-dev bf2bee2  A PHP library for generating and working with universally unique identifiers (UUIDs).
sebastian/cli-parser                 2.0.0            Library for parsing CLI options
sebastian/code-unit                  2.0.0            Collection of value objects that represent the PHP code units
sebastian/code-unit-reverse-lookup   3.0.0            Looks up which function or method a line of code belongs to
sebastian/comparator                 5.0.0            Provides the functionality to compare PHP values for equality
sebastian/complexity                 3.0.0            Library for calculating the complexity of PHP code units
sebastian/diff                       5.0.0            Diff implementation
sebastian/environment                6.0.0            Provides functionality to handle HHVM/PHP environments
sebastian/exporter                   5.0.0            Provides the functionality to export PHP variables for visualization
sebastian/global-state               6.0.0            Snapshotting of global state
sebastian/lines-of-code              2.0.0            Library for counting the lines of code in PHP source code
sebastian/object-enumerator          5.0.0            Traverses array structures and object graphs to enumerate all referenced objects
sebastian/object-reflector           3.0.0            Allows reflection of object attributes, including inherited and non-public ones
sebastian/recursion-context          5.0.0            Provides functionality to recursively process PHP variables
sebastian/type                       4.0.0            Collection of value objects that represent the types of the PHP type system
sebastian/version                    4.0.1            Library that helps with managing the version number of Git-hosted PHP projects
seld/jsonlint                        1.9.0            JSON Linter
spatie/fractalistic                  2.9.5            A developer friendly wrapper around Fractal
spatie/laravel-fractal               6.0.3            An easy to use Fractal integration for Laravel applications
spatie/laravel-package-tools         1.14.2           Tools for creating Laravel packages
symfony/config                       v6.2.7           Helps you find, load, combine, autofill and validate configuration values of any kind
symfony/console                      v6.2.7           Eases the creation of beautiful and testable command line interfaces
symfony/css-selector                 v6.2.7           Converts CSS selectors to XPath expressions
symfony/dependency-injection         v6.2.7           Allows you to standardize and centralize the way objects are constructed in your application
symfony/deprecation-contracts        v3.2.1           A generic function and convention to trigger deprecation notices
symfony/dotenv                       v6.2.7           Registers environment variables from a .env file
symfony/error-handler                v6.2.7           Provides tools to manage errors and ease debugging PHP code
symfony/event-dispatcher             v6.2.7           Provides tools that allow your application components to communicate with each other by dispatching events and listening to them
symfony/event-dispatcher-contracts   v3.2.1           Generic abstractions related to dispatching event
symfony/filesystem                   v6.2.7           Provides basic utilities for the filesystem
symfony/finder                       v6.2.7           Finds files and directories via an intuitive fluent interface
symfony/http-foundation              v6.2.7           Defines an object-oriented layer for the HTTP specification
symfony/http-kernel                  v6.2.7           Provides a structured process for converting a Request into a Response
symfony/mailer                       v6.2.7           Helps sending emails
symfony/mime                         v6.2.7           Allows manipulating MIME messages
symfony/options-resolver             v6.2.7           Provides an improved replacement for the array_replace PHP function
symfony/polyfill-ctype               v1.27.0          Symfony polyfill for ctype functions
symfony/polyfill-intl-grapheme       v1.27.0          Symfony polyfill for intl's grapheme_* functions
symfony/polyfill-intl-idn            v1.27.0          Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions
symfony/polyfill-intl-normalizer     v1.27.0          Symfony polyfill for intl's Normalizer class and related functions
symfony/polyfill-mbstring            v1.27.0          Symfony polyfill for the Mbstring extension
symfony/polyfill-php72               v1.27.0          Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions
symfony/polyfill-php80               v1.27.0          Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions
symfony/polyfill-php81               v1.27.0          Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions
symfony/polyfill-uuid                v1.27.0          Symfony polyfill for uuid functions
symfony/process                      v6.2.7           Executes commands in sub-processes
symfony/routing                      v6.2.7           Maps an HTTP request to a set of configuration variables
symfony/service-contracts            v3.2.1           Generic abstractions related to writing services
symfony/stopwatch                    v6.2.7           Provides a way to profile code
symfony/string                       v6.2.7           Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way
symfony/translation                  v6.2.7           Provides tools to internationalize your application
symfony/translation-contracts        v3.2.1           Generic abstractions related to translation
symfony/uid                          v6.2.7           Provides an object-oriented API to generate and represent UIDs
symfony/var-dumper                   v6.2.7           Provides mechanisms for walking through any arbitrary PHP variable
symfony/var-exporter                 v6.2.7           Allows exporting any serializable PHP data structure to plain PHP code
symfony/yaml                         v6.2.7           Loads and dumps YAML files
theseer/tokenizer                    1.2.1            A small library for converting tokenized PHP source code into XML and potentially other formats
tijsverkoyen/css-to-inline-styles    2.2.6            CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you're sending emails.
vlucas/phpdotenv                     v5.5.0           Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.
voku/portable-ascii                  2.0.1            Portable ASCII library - performance optimized (ascii) string functions for php.
webmozart/assert                     1.11.0           Assertions to validate method input/output with nice error messages.

Summary

I'm using the Laravel framework and trying to create a simple stub for the final class Symfony\Component\Console\Helper\ProgressBar (I'm writing a unit test for the console command):

// test file
use Illuminate\Foundation\Testing\TestCase;

class MyCommandTest extends TestCase
{
    use CreatesApplication;

    public function test(): void
    {
        $progressBarMock = new class {
            public function start(): void
            {}
            public function advance(): void
            {}
            public function finish(): void
            {}
        };

        $outputStyleMock = $this->createMock(OutputStyle::class);
        $outputStyleMock
            ->expects($this->once())
            ->method('createProgressBar')
            ->willReturn($progressBarMock);
        $command = $this->createMock(MyCommand::class); // in real code I use `getMockBuilder()` but it doesn't matter
        $command->setOutput($outputStyleMock);
    }
}

// command file
use Illuminate\Console\Command;

class MyCommand extends Command
{
    protected $signature = 'mycommand:run';
    protected $description = 'My awesome command';

    public function handle(): int
    {
        $total = 100;
        $progressBar = $this->output->createProgressBar($total);
        $progressBar->start();

        for ($i = 0; $i < $total; $i++) {
            // some logic here
            $progressBar->advance();
        }

        $progressBar->finish();

        return 0;
    }
}

Current behavior

Method createProgressBar may not return value of type class@anonymous, its declared return type is "Symfony\Component\Console\Helper\ProgressBar"

How to reproduce

Run the code snippet provided above

Expected behavior

No errors expected (as in PHPUnit 9)

sebastianbergmann commented 1 year ago

Thank you for your report.

Please provide a minimal, self-contained, reproducing test case that shows the problem you are reporting.

Without such a minimal, self-contained, reproducing test case I will not be able to investigate this issue.

NickSun commented 1 year ago

@sebastianbergmann please check this repository https://github.com/NickSun/phpunit-10-issue

sebastianbergmann commented 1 year ago

There is no bug here, what you want to do is simply not possible.

Using new class (and not new class implements ... or new class extends ...) you create an anonymous class that has no relationship to the type that is used in the return type declaration. Thus the object cannot be used as a return value for the method.