Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test Double code generator does not handle "void" return type declaration on __clone() methods #4938

Closed
recipe opened this issue Mar 23, 2022 · 1 comment
Assignees
Labels
feature/test-doubles Test Stubs and Mock Objects type/change-in-php-requires-adaptation A change in PHP requires a change so that existing PHPUnit functionality continues to work

Comments

@recipe
Copy link

recipe commented Mar 23, 2022

Q A
PHPUnit version 9.5.19
PHP version 8.1.2
Installation Method Composer

Summary

phpunit fails with the following error:

Fatal error: Declaration of PHPUnit\Framework\MockObject\UnmockedCloneMethod::__clone() must be compatible with Foo\Model\Entity\Account::__clone(): void in /usr/local/src/foo/vendor/phpunit/phpunit/src/Framework/MockObject/Api/UnmockedCloneMethod.php on line 17

Current behavior

phpunit tests is unable to start.

How to reproduce

<?php

namespace Foo\Tests;

use PHPUnit\Framework\TestCase as PHPUnitTestCase;

class Account
{
    public function __clone(): void
    {
    }
}
class FooTest extends PHPUnitTestCase
{
    public function testFoo()
    {
        $mock = $this->getMockBuilder(Account::class)->getMock();
    }
}
  • Account class has the following declaration of the __clone method: public function __clone(): void

Expected behavior

If I specify the return type of UnmockedCloneMethod::__clone() method as this, the problem is fixed:

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

/**
 * @internal This trait is not covered by the backward compatibility promise for PHPUnit
 */
trait UnmockedCloneMethod
{
    public function __clone(): void
    {
        $this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationHandler();

        parent::__clone();
    }
}

composer info | sort

adodb/adodb-php                    dev-master d54f74d ADOdb is a PHP database abstraction layer library
bitbucket/client                   dev-master 70e8008 Bitbucket API 2.0 client for PHP
brianium/paratest                  v6.4.3             Parallel testing for PHP
cebe/markdown                      1.2.1              A super fast, highly extensible markdown parser for PHP
cebe/php-openapi                   1.6.0              Read and write OpenAPI yaml/json files and make the content accessable in PHP objects.
clue/stream-filter                 v1.5.0             A simple and modern approach to stream filtering in PHP
composer/pcre                      1.0.1              PCRE wrapping library that offers type-safe preg_* replacements.
composer/semver                    3.2.9              Semver library that offers utilities, version constraint parsing and validation.
composer/xdebug-handler            3.0.1              Restarts a process without Xdebug.
doctrine/annotations               1.13.2             Docblock Annotations Parser
doctrine/instantiator              1.4.1              A small, lightweight utility to instantiate objects in PHP without invoking their constructors
doctrine/lexer                     1.2.2              PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.
fakerphp/faker                     v1.19.0            Faker is a PHP library that generates fake data for you.
firebase/php-jwt                   v5.0.0             A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.
friendsofphp/php-cs-fixer          v3.6.0             A tool to automatically fix PHP code style
google/apiclient-services          v0.234.0           Client library for Google APIs
google/apiclient                   v2.12.1            Client library for Google APIs
google/auth                        v1.18.0            Google Auth Library for PHP
guzzlehttp/guzzle                  7.4.1              Guzzle is a PHP HTTP client library
guzzlehttp/promises                1.5.1              Guzzle promises library
guzzlehttp/psr7                    2.1.0              PSR-7 message implementation that also provides common utility methods
justinrainbow/json-schema          5.2.11             A library to validate a json schema.
knplabs/github-api                 v3.5.0             GitHub API v3 client
league/oauth1-client               v1.10.0            OAuth 1.0 Client Library
league/oauth2-client               2.6.1              OAuth 2.0 Client Library
league/oauth2-github               2.0.0              Github OAuth 2.0 Client Provider for The PHP League OAuth2-Client
league/oauth2-google               4.0.0              Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client
league/openapi-psr7-validator      0.16.4             Validate PSR-7 messages against OpenAPI (3.0.2) specifications expressed in YAML or JSON
league/uri                         6.5.0              URI manipulation library
league/uri-interfaces              2.3.0              Common interface for URI representation
m4tthumphrey/php-gitlab-api        11.7.0             GitLab API v4 client for PHP
monolog/monolog                    1.26.1             Sends your logs to files, sockets, inboxes, databases and various web services
myclabs/deep-copy                  1.11.0             Create deep copies (clones) of your objects
nelmio/alice                       v3.10.0            Expressive fixtures generator
nikic/php-parser                   v4.13.2            A PHP parser written in PHP
nyholm/psr7                        1.5.0              A fast PHP7 implementation of PSR-7
omines/oauth2-gitlab               3.4.0              GitLab OAuth 2.0 Client Provider for The PHP League OAuth2-Client
onelogin/php-saml                  4.0.0              OneLogin PHP SAML Toolkit
paragonie/constant_time_encoding   v2.5.0             Constant-time Implementations of RFC 4648 Encoding (Base-64, Base-32, Base-16)
paragonie/random_compat            v9.99.100          PHP 5.x polyfill for random_bytes() and random_int() from PHP 7
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
php-amqplib/php-amqplib            v3.1.2             Formerly videlalvaro/php-amqplib.  This library is a pure PHP implementation of the AMQP protocol. It's been tested agai...
php-cs-fixer/diff                  v2.0.2             sebastian/diff v3 backport support for PHP 5.6+
phpdocumentor/reflection-common    2.2.0              Common reflection classes used by phpdocumentor to reflect the code structure
phpdocumentor/reflection-docblock  5.3.0              With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that ...
phpdocumentor/type-resolver        1.6.0              A PSR-5 based resolver of Class names, Types and Structural Element Names
php-http/cache-plugin              1.7.5              PSR-6 Cache plugin for HTTPlug
php-http/client-common             2.5.0              Common HTTP Client implementations and tools for HTTPlug
php-http/discovery                 1.14.1             Finds installed HTTPlug implementations and PSR-7 message factories
php-http/guzzle7-adapter           1.0.0              Guzzle 7 HTTP Adapter
php-http/httplug                   2.2.0              HTTPlug, the HTTP client abstraction for PHP
php-http/message                   1.12.0             HTTP Message related tools
php-http/message-factory           v1.0.2             Factory interfaces for PSR-7 HTTP Message
php-http/multipart-stream-builder  1.2.0              A builder class that help you create a multipart stream
php-http/promise                   1.1.0              Promise used for asynchronous HTTP requests
phpseclib/phpseclib                3.0.13             PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.
phpspec/prophecy                   v1.15.0            Highly opinionated mocking framework for PHP 5.3+
phpunit/php-code-coverage          9.2.15             Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator          3.0.6              FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-invoker                3.1.1              Invoke callables with a timeout
phpunit/php-text-template          2.0.4              Simple template engine.
phpunit/php-timer                  5.0.3              Utility class for timing
phpunit/phpunit                    9.5.19             The PHP Unit Testing framework.
psr/cache                          1.0.1              Common interface for caching libraries
psr/container                      1.1.2              Common Container Interface (PHP FIG PSR-11)
psr/event-dispatcher               1.0.0              Standard interfaces for event handling.
psr/http-client                    1.0.1              Common interface for HTTP clients
psr/http-factory                   1.0.1              Common interfaces for PSR-7 HTTP message factories
psr/http-message                   1.0.1              Common interface for HTTP messages
psr/http-server-handler            1.0.1              Common interface for HTTP server-side request handler
psr/http-server-middleware         1.0.1              Common interface for HTTP server-side middleware
psr/log                            1.1.4              Common interface for logging libraries
psr/simple-cache                   1.0.0              Common interfaces for simple caching
ralouphie/getallheaders            3.0.3              A polyfill for getallheaders.
respect/stringifier                0.2.0              Converts any value to a string
respect/validation                 2.2.3              The most awesome validation engine ever created for PHP
riverline/multipart-parser         2.0.9              One class library to parse multipart content with encoding and charset support.
robrichards/xmlseclibs             3.1.1              A PHP library for XML Security
sebastian/cli-parser               1.0.1              Library for parsing CLI options
sebastian/code-unit                1.0.8              Collection of value objects that represent the PHP code units
sebastian/code-unit-reverse-lookup 2.0.3              Looks up which function or method a line of code belongs to
sebastian/comparator               4.0.6              Provides the functionality to compare PHP values for equality
sebastian/complexity               2.0.2              Library for calculating the complexity of PHP code units
sebastian/diff                     4.0.4              Diff implementation
sebastian/environment              5.1.3              Provides functionality to handle HHVM/PHP environments
sebastian/exporter                 4.0.4              Provides the functionality to export PHP variables for visualization
sebastian/global-state             5.0.5              Snapshotting of global state
sebastian/lines-of-code            1.0.3              Library for counting the lines of code in PHP source code
sebastian/object-enumerator        4.0.4              Traverses array structures and object graphs to enumerate all referenced objects
sebastian/object-reflector         2.0.4              Allows reflection of object attributes, including inherited and non-public ones
sebastian/recursion-context        4.0.4              Provides functionality to recursively process PHP variables
sebastian/resource-operations      3.0.3              Provides a list of PHP built-in functions that operate on resources
sebastian/type                     3.0.0              Collection of value objects that represent the types of the PHP type system
sebastian/version                  3.0.2              Library that helps with managing the version number of Git-hosted PHP projects
segmentio/analytics-php            2.0.0              Segment Analytics PHP Library
stevenmaguire/oauth2-bitbucket     3.0.0              Bitbucket OAuth 2.0 Client Provider for The PHP League OAuth2-Client
symfony/cache-contracts            v2.5.0             Generic abstractions related to caching
symfony/cache                      v4.4.37            Provides an extended PSR-6, PSR-16 (and tags) implementation
symfony/console                    v6.0.5             Eases the creation of beautiful and testable command line interfaces
symfony/deprecation-contracts      v3.0.0             A generic function and convention to trigger deprecation notices
symfony/event-dispatcher-contracts v3.0.0             Generic abstractions related to dispatching event
symfony/event-dispatcher           v6.0.3             Provides tools that allow your application components to communicate with each other by dispatching events and listening...
symfony/filesystem                 v6.0.3             Provides basic utilities for the filesystem
symfony/finder                     v6.0.3             Finds files and directories via an intuitive fluent interface
symfony/options-resolver           v6.0.3             Provides an improved replacement for the array_replace PHP function
symfony/polyfill-ctype             v1.25.0            Symfony polyfill for ctype functions
symfony/polyfill-intl-grapheme     v1.25.0            Symfony polyfill for intl's grapheme_* functions
symfony/polyfill-intl-normalizer   v1.25.0            Symfony polyfill for intl's Normalizer class and related functions
symfony/polyfill-mbstring          v1.25.0            Symfony polyfill for the Mbstring extension
symfony/polyfill-php73             v1.25.0            Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions
symfony/polyfill-php80             v1.25.0            Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions
symfony/polyfill-php81             v1.24.0            Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions
symfony/process                    v6.0.5             Executes commands in sub-processes
symfony/property-access            v6.0.3             Provides functions to read and write from/to an object or array using a simple string notation
symfony/property-info              v6.0.3             Extracts information about PHP class' properties using metadata of popular sources
symfony/service-contracts          v2.4.1             Generic abstractions related to writing services
symfony/stopwatch                  v6.0.3             Provides a way to profile code
symfony/string                     v6.0.3             Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way
symfony/var-exporter               v5.4.3             Allows exporting any serializable PHP data structure to plain PHP code
symfony/yaml                       v6.0.3             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
webmozart/assert                   1.10.0             Assertions to validate method input/output with nice error messages.
zircote/swagger-php                4.2.6              swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations
@recipe recipe added the type/bug Something is broken label Mar 23, 2022
@sebastianbergmann sebastianbergmann self-assigned this Mar 24, 2022
@sebastianbergmann sebastianbergmann added the feature/test-doubles Test Stubs and Mock Objects label Mar 24, 2022
@sebastianbergmann
Copy link
Owner

Thank you for bringing this to my attention. I was not aware that __clone() can be declared void since PHP 8.0.

@sebastianbergmann sebastianbergmann added type/change-in-php-requires-adaptation A change in PHP requires a change so that existing PHPUnit functionality continues to work and removed type/bug Something is broken labels Mar 24, 2022
@sebastianbergmann sebastianbergmann changed the title UnmockedCloneMethod::__clone() must be compatible with the Class::__clone(): void Test Double code generator does not handle "void" return type declaration on __clone() methods Mar 24, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature/test-doubles Test Stubs and Mock Objects type/change-in-php-requires-adaptation A change in PHP requires a change so that existing PHPUnit functionality continues to work
Projects
None yet
Development

No branches or pull requests

2 participants