Skip to content

Commit

Permalink
[TASK] Provide a test to demonstrate a regresision
Browse files Browse the repository at this point in the history
This change adds a fixture class and a MockBuilder test
to showcase a regression introduced with version 11.2.0.

Given is a class, where one method is mocked using the
`onlyMethods()` option to check the method gets called.
The method is called in the class constructor and also
in other public method.

Providing a test mocking that method this breaks since
11.2.0 - albeit having the count in previous version
only working for calls to the mock method AFTER the
constructor call.

Following exception thrown is not expectd:

    Error: Typed property
    MockObject_ClassCallingMethodInConstructor_b5ada611::$__phpunit_state
    must not be accessed before initialization

Related: #5857
  • Loading branch information
sbuerk authored and sebastianbergmann committed Jun 9, 2024
1 parent deccf9e commit e5b3c30
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\TestFixture\MockObject;

class ClassCallingMethodInConstructor
{
public function __construct()
{
$this->reset();
}

public function reset(): void
{
}

public function second(): void
{
$this->reset();
}
}
12 changes: 12 additions & 0 deletions tests/unit/Framework/MockObject/Creation/MockBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\MockObject;

use PHPUnit\TestFixture\MockObject\ClassCallingMethodInConstructor;
use function assert;
use function class_exists;
use function interface_exists;
Expand Down Expand Up @@ -165,4 +166,15 @@ public function testCreatesMockObjectForUnknownType(): void
$this->assertInstanceOf(MockObject::class, $double);

}

#[TestDox('onlyMethods() mocked methods can be called within the original constructor')]
public function testOnlyMethodCalledInConstructorWorks(): void
{
$testClassMock = $this->getMockBuilder(ClassCallingMethodInConstructor::class)
->onlyMethods(['reset'])
->getMock();

$testClassMock->expects($this::once())->method('reset');
$testClassMock->second();
}
}

0 comments on commit e5b3c30

Please sign in to comment.