Skip to content

Class constant as default parameter is undefined #3801

@gleb-svitelskiy

Description

@gleb-svitelskiy
Q A
PHPUnit version 8.3.4
PHP version 7.2.21
Installation Method Composer / PHAR (error occurs in both)

There is an error when private constant is default value in method parameter.

Minimal test file:

<?php

use PHPUnit\Framework\TestCase;

class SomeClass
{
    private const CLASS_CONSTANT = 42;
    public function someMethod(int $value = self::CLASS_CONSTANT)
    {
        return $value;
    }
}

class SomeClassTest extends TestCase
{
    public function testSomeMethod()
    {
        $stub = $this->createMock(SomeClass::class);
        $stub->method('someMethod')->willReturn(42);
        $this->assertSame(42, $stub->someMethod());
    }
}

Example execution via phpunit.phar:

root@48a85a9a7259:/# phpunit /usr/src/SomeClassTest.php
PHPUnit 8.3.4 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 67 ms, Memory: 10.00 MB

There was 1 error:

1) SomeClassTest::testSomeMethod
Error: Undefined class constant 'self::CLASS_CONSTANT'

/usr/src/SomeClassTest.php:20

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

I dig a little deeper and find the issue. There are some changes in PHPUnit with constants handle when mock method is creating - 83722bc. And here is the reason - sebastianbergmann/phpunit-mock-objects#419.
That was a PHP bug and I found it in PHP changelog:
Fixed bug #76717 (var_export() does not create a parsable value for PHP_INT_MIN)
https://bugs.php.net/bug.php?id=76717
This fix is released in versions 7.2.17 and 7.3.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions