Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Mocking a class with a property hook setter accepting more types than the property results in a fatal error #6470

@Vassyli

Description

@Vassyli
Q A
PHPUnit version 12.5.4
PHP version 8.4.10
Installation Method Composer / PHAR

Summary

With property hooks, a setter can be configured to accept more types than the property itself, giving the possibility to convert inside the setter. Creating mocks of classes with such property hooks results in Fatal Errors.

Current behavior

PHPUnit quits with a Fatal Error:

Fatal error: Declaration of MockObject_PropertyHookSet_1b26a8f5::$integer::set(?int $value): void must be compatible with Tests\PropertyHookSet::$integer::set(string|int|float|bool|null $value): void in [...]/vendor/phpunit/phpunit/src/Framework/MockObject/Generator/DoubledClass.php(51) : eval()'d code on line 19

How to reproduce

<?php
declare(strict_types=1);

namespace Tests;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DoesNotPerformAssertions;
use PHPUnit\Framework\TestCase;

class PropertyHookSet {
    public ?int $integer = null {
        get => $this->integer;
        set(string|float|int|bool|null $value) {
            $this->integer = (int)$value;
        }
    }
}

#[CoversClass(PropertyHookSet::class)]
class PhpUnitTest extends TestCase
{
    # Passes as expected
    public function testNormalUsage()
    {
        $propertyHook = new PropertyHookSet();
        $propertyHook->integer = 5;

        $this->assertSame(5, $propertyHook->integer);

        $propertyHook->integer = "5";

        $this->assertSame(5, $propertyHook->integer);
    }

    #Fails with a Fatal error
    #[DoesNotPerformAssertions]
    public function testSomething()
    {
        $mock = $this->createMock(PropertyHookSet::class);
    }
}

Expected behavior

Mock or Stub should get created without issues.

composer info | sort

doctrine/collections                2.4.0  PHP Doctrine Collections library that adds additional functionality on top of PHP arrays.
doctrine/data-fixtures              2.2.0  Data Fixtures for all Doctrine Object Managers
doctrine/dbal                       4.4.1  Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.
doctrine/deprecations               1.1.5  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/doctrine-bundle            2.18.1 Symfony DoctrineBundle
doctrine/doctrine-fixtures-bundle   3.7.3  Symfony DoctrineFixturesBundle
doctrine/doctrine-migrations-bundle 3.7.0  Symfony DoctrineMigrationsBundle
doctrine/event-manager              2.0.1  The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.
doctrine/inflector                  2.1.0  PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.
doctrine/instantiator               2.0.0  A small, lightweight utility to instantiate objects in PHP without invoking their constructors
doctrine/lexer                      3.0.1  PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.
doctrine/migrations                 3.9.5  PHP Doctrine Migrations project offer additional functionality on top of the database abstraction layer (DBAL) for versioning your database schema and easily deploying changes to it. It is a very e...  
doctrine/orm                        3.5.8  Object-Relational-Mapper for PHP
doctrine/persistence                4.1.1  The Doctrine Persistence project is a set of shared interfaces and functionality that the different Doctrine object mappers share.
doctrine/sql-formatter              1.5.3  a PHP SQL highlighting library
dunglas/doctrine-json-odm           1.4.2  An object document mapper for Doctrine ORM using JSON types of modern RDBMS.
egulias/email-validator             4.0.4  A library for validating emails against several RFCs
gglnx/twig-try-catch                1.0.0  Adds exception handling to Twig
masterminds/html5                   2.10.0 An HTML5 parser and serializer.
monolog/monolog                     3.9.0  Sends your logs to files, sockets, inboxes, databases and various web services
myclabs/deep-copy                   1.13.4 Create deep copies (clones) of your objects
nelmio/cors-bundle                  2.6.0  Adds CORS (Cross-Origin Resource Sharing) headers support in your Symfony application
nikic/php-parser                    5.7.0  A PHP parser written in PHP
phar-io/manifest                    2.0.4  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
phpdocumentor/reflection-common     2.2.0  Common reflection classes used by phpdocumentor to reflect the code structure
phpdocumentor/reflection-docblock   5.6.5  With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.
phpdocumentor/type-resolver         1.12.0 A PSR-5 based resolver of Class names, Types and Structural Element Names
phpstan/extension-installer         1.4.3  Composer plugin for automatic installation of PHPStan extensions
phpstan/phpdoc-parser               1.33.0 PHPDoc parser with support for nullable, intersection and generic types
phpstan/phpstan                     2.1.33 PHPStan - PHP Static Analysis Tool
phpstan/phpstan-doctrine            2.0.12 Doctrine extensions for PHPStan
phpstan/phpstan-symfony             2.0.9  Symfony Framework extensions and rules for PHPStan
phpunit/php-code-coverage           12.5.1 Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator           6.0.0  FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-invoker                 6.0.0  Invoke callables with a timeout
phpunit/php-text-template           5.0.0  Simple template engine.
phpunit/php-timer                   8.0.0  Utility class for timing
phpunit/phpunit                     12.5.4 The PHP Unit Testing framework.
psr/cache                           3.0.0  Common interface for caching libraries
psr/clock                           1.0.0  Common interface for reading the clock.
psr/container                       2.0.2  Common Container Interface (PHP FIG PSR-11)
psr/event-dispatcher                1.0.0  Standard interfaces for event handling.
psr/link                            2.0.1  Common interfaces for HTTP links
psr/log                             3.0.2  Common interface for logging libraries
sebastian/cli-parser                4.2.0  Library for parsing CLI options
sebastian/comparator                7.1.3  Provides the functionality to compare PHP values for equality
sebastian/complexity                5.0.0  Library for calculating the complexity of PHP code units
sebastian/diff                      7.0.0  Diff implementation
sebastian/environment               8.0.3  Provides functionality to handle HHVM/PHP environments
sebastian/exporter                  7.0.2  Provides the functionality to export PHP variables for visualization
sebastian/global-state              8.0.2  Snapshotting of global state
sebastian/lines-of-code             4.0.0  Library for counting the lines of code in PHP source code
sebastian/object-enumerator         7.0.0  Traverses array structures and object graphs to enumerate all referenced objects
sebastian/object-reflector          5.0.0  Allows reflection of object attributes, including inherited and non-public ones
sebastian/recursion-context         7.0.1  Provides functionality to recursively process PHP variables
sebastian/type                      6.0.3  Collection of value objects that represent the types of the PHP type system
sebastian/version                   6.0.0  Library that helps with managing the version number of Git-hosted PHP projects
staabm/side-effects-detector        1.0.5  A static analysis tool to detect side effects in PHP code
symfony/asset                       7.4.0  Manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files and image files
symfony/browser-kit                 7.4.0  Simulates the behavior of a web browser, allowing you to make requests, click on links and submit forms programmatically
symfony/cache                       7.4.1  Provides extended PSR-6, PSR-16 (and tags) implementations
symfony/cache-contracts             3.6.0  Generic abstractions related to caching
symfony/clock                       7.4.0  Decouples applications from the system clock
symfony/config                      7.4.1  Helps you find, load, combine, autofill and validate configuration values of any kind
symfony/console                     7.4.1  Eases the creation of beautiful and testable command line interfaces
symfony/css-selector                7.4.0  Converts CSS selectors to XPath expressions
symfony/debug-bundle                7.4.0  Provides a tight integration of the Symfony VarDumper component and the ServerLogCommand from MonologBridge into the Symfony full-stack framework
symfony/dependency-injection        7.4.2  Allows you to standardize and centralize the way objects are constructed in your application
symfony/deprecation-contracts       3.6.0  A generic function and convention to trigger deprecation notices
symfony/doctrine-bridge             7.4.1  Provides integration for Doctrine with various Symfony components
symfony/dom-crawler                 7.4.1  Eases DOM navigation for HTML and XML documents
symfony/dotenv                      7.4.0  Registers environment variables from a .env file
symfony/error-handler               7.4.0  Provides tools to manage errors and ease debugging PHP code
symfony/event-dispatcher            7.4.0  Provides tools that allow your application components to communicate with each other by dispatching events and listening to them
symfony/event-dispatcher-contracts  3.6.0  Generic abstractions related to dispatching event
symfony/expression-language         7.4.0  Provides an engine that can compile and evaluate expressions
symfony/filesystem                  7.4.0  Provides basic utilities for the filesystem
symfony/finder                      7.4.0  Finds files and directories via an intuitive fluent interface
symfony/flex                        2.10.0 Composer plugin for Symfony
symfony/form                        7.4.1  Allows to easily create, process and reuse HTML forms
symfony/framework-bundle            7.4.1  Provides a tight integration between Symfony components and the Symfony full-stack framework
symfony/http-client                 7.4.1  Provides powerful methods to fetch HTTP resources synchronously or asynchronously
symfony/http-client-contracts       3.6.0  Generic abstractions related to HTTP clients
symfony/http-foundation             7.4.1  Defines an object-oriented layer for the HTTP specification
symfony/http-kernel                 7.4.2  Provides a structured process for converting a Request into a Response
symfony/intl                        7.4.0  Provides access to the localization data of the ICU library
symfony/mailer                      7.4.0  Helps sending emails
symfony/maker-bundle                1.65.1 Symfony Maker helps you create empty commands, controllers, form classes, tests and more so you can forget about writing boilerplate code.
symfony/mime                        7.4.0  Allows manipulating MIME messages
symfony/monolog-bridge              7.4.0  Provides integration for Monolog with various Symfony components
symfony/monolog-bundle              3.11.1 Symfony MonologBundle
symfony/notifier                    7.4.0  Sends notifications via one or more channels (email, SMS, ...)
symfony/options-resolver            7.4.0  Provides an improved replacement for the array_replace PHP function
symfony/password-hasher             7.4.0  Provides password hashing utilities
symfony/phpunit-bridge              6.4.26 Provides utilities for PHPUnit, especially user deprecation notices management
symfony/polyfill-intl-grapheme      1.33.0 Symfony polyfill for intl's grapheme_* functions
symfony/polyfill-intl-icu           1.33.0 Symfony polyfill for intl's ICU-related data and classes
symfony/polyfill-intl-idn           1.33.0 Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions
symfony/polyfill-intl-normalizer    1.33.0 Symfony polyfill for intl's Normalizer class and related functions
symfony/polyfill-mbstring           1.33.0 Symfony polyfill for the Mbstring extension
symfony/polyfill-php83              1.33.0 Symfony polyfill backporting some PHP 8.3+ features to lower PHP versions
symfony/polyfill-php84              1.33.0 Symfony polyfill backporting some PHP 8.4+ features to lower PHP versions
symfony/polyfill-php85              1.33.0 Symfony polyfill backporting some PHP 8.5+ features to lower PHP versions
symfony/process                     7.4.0  Executes commands in sub-processes
symfony/property-access             7.4.0  Provides functions to read and write from/to an object or array using a simple string notation
symfony/property-info               7.4.1  Extracts information about PHP class' properties using metadata of popular sources
symfony/routing                     7.4.0  Maps an HTTP request to a set of configuration variables
symfony/runtime                     7.4.1  Enables decoupling PHP applications from global state
symfony/security-bundle             7.4.0  Provides a tight integration of the Security component into the Symfony full-stack framework
symfony/security-core               7.4.0  Symfony Security Component - Core Library
symfony/security-csrf               7.4.0  Symfony Security Component - CSRF Library
symfony/security-http               7.4.1  Symfony Security Component - HTTP Integration
symfony/serializer                  7.4.2  Handles serializing and deserializing data structures, including object graphs, into array structures or other formats like XML and JSON.
symfony/service-contracts           3.6.1  Generic abstractions related to writing services
symfony/stimulus-bundle             2.31.0 Integration with your Symfony app & Stimulus!
symfony/stopwatch                   7.4.0  Provides a way to profile code
symfony/string                      7.4.0  Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way
symfony/translation                 7.4.0  Provides tools to internationalize your application
symfony/translation-contracts       3.6.1  Generic abstractions related to translation
symfony/twig-bridge                 7.4.1  Provides integration for Twig with various Symfony components
symfony/twig-bundle                 7.4.0  Provides a tight integration of Twig into the Symfony full-stack framework
symfony/type-info                   7.4.1  Extracts PHP types information.
symfony/ux-live-component           2.31.0 Live components for Symfony
symfony/ux-turbo                    2.31.0 Hotwire Turbo integration for Symfony
symfony/ux-twig-component           2.31.0 Twig components for Symfony
symfony/ux-vue                      2.31.0 Integration of Vue.js in Symfony
symfony/validator                   7.4.2  Provides tools to validate values
symfony/var-dumper                  7.4.0  Provides mechanisms for walking through any arbitrary PHP variable
symfony/var-exporter                7.4.0  Allows exporting any serializable PHP data structure to plain PHP code
symfony/web-link                    7.4.0  Manages links between resources
symfony/web-profiler-bundle         7.4.0  Provides a development tool that gives detailed information about the execution of any request
symfony/webpack-encore-bundle       2.4.0  Integration of your Symfony app with Webpack Encore
symfony/yaml                        7.4.1  Loads and dumps YAML files
theseer/tokenizer                   2.0.1  A small library for converting tokenized PHP source code into XML and potentially other formats
twig/extra-bundle                   3.22.2 A Symfony bundle for extra Twig extensions
twig/twig                           3.22.2 Twig, the flexible, fast, and secure template language for PHP
webmozart/assert                    1.12.1 Assertions to validate method input/output with nice error messages.

phpunit --check-php-configuration

PHPUnit 12.5.4 by Sebastian Bergmann and contributors.

Checking whether PHP is configured according to https://docs.phpunit.de/en/12.5/installation.html#configuring-php-for-development

display_errors = On             ... not ok ()
display_startup_errors = On     ... not ok ()
error_reporting = -1            ... not ok (22527)
xdebug.show_exception_trace = 0 ... ok
zend.assertions = 1             ... not ok (-1)
assert.exception = 1            ... ok
memory_limit = -1               ... ok

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions