diff --git a/src/Framework/MockObject/Generator.php b/src/Framework/MockObject/Generator.php index ec9aae591b0..f3442a70a44 100644 --- a/src/Framework/MockObject/Generator.php +++ b/src/Framework/MockObject/Generator.php @@ -747,23 +747,49 @@ private function generateMock($type, $explicitMethods, $mockClassName, $callOrig // @see https://github.com/sebastianbergmann/phpunit/issues/2995 if ($isInterface && $class->implementsInterface(\Throwable::class)) { + $actualClassName = \Exception::class; $additionalInterfaces[] = $class->getName(); - $interfaceOwnMethods = []; $isInterface = false; - foreach ($this->getInterfaceOwnMethods($mockClassName['fullClassName']) as $method) { - $interfaceOwnMethods[] = MockMethod::fromReflection($method, $callOriginalMethods, $cloneArguments); + try { + $class = new \ReflectionClass($actualClassName); + } catch (\ReflectionException $e) { + throw new RuntimeException( + $e->getMessage(), + (int) $e->getCode(), + $e + ); } - $mockMethods->addMethods(...$interfaceOwnMethods); + foreach ($this->getInterfaceOwnMethods($mockClassName['fullClassName']) as $method) { + $methodName = $method->getName(); + + if ($class->hasMethod($methodName)) { + try { + $classMethod = $class->getMethod($methodName); + } catch (\ReflectionException $e) { + throw new RuntimeException( + $e->getMessage(), + (int) $e->getCode(), + $e + ); + } + + if (!$this->canMockMethod($classMethod)) { + continue; + } + } + + $mockMethods->addMethods( + MockMethod::fromReflection($method, $callOriginalMethods, $cloneArguments) + ); + } $mockClassName = $this->generateClassName( - \Exception::class, + $actualClassName, '', 'Mock_' ); - - $class = new ReflectionClass($mockClassName['fullClassName']); } // https://github.com/sebastianbergmann/phpunit-mock-objects/issues/103 diff --git a/tests/unit/Framework/MockObject/GeneratorTest.php b/tests/unit/Framework/MockObject/GeneratorTest.php index bc39b8d10aa..51d1ebe42d4 100644 --- a/tests/unit/Framework/MockObject/GeneratorTest.php +++ b/tests/unit/Framework/MockObject/GeneratorTest.php @@ -202,7 +202,7 @@ public function testCanInvokeMethodsOfNonExistentClass(): void $this->assertNull($mock->someMethod()); } - public function testMockingOfThrowable(): void + public function testMockingOfExceptionWithThrowable(): void { $stub = $this->generator->getMock(ExceptionWithThrowable::class); @@ -211,6 +211,15 @@ public function testMockingOfThrowable(): void $this->assertInstanceOf(MockObject::class, $stub); } + public function testMockingOfThrowable(): void + { + $stub = $this->generator->getMock(Throwable::class); + + $this->assertInstanceOf(Throwable::class, $stub); + $this->assertInstanceOf(Exception::class, $stub); + $this->assertInstanceOf(MockObject::class, $stub); + } + public function testVariadicArgumentsArePassedToOriginalMethod() { /** @var ClassWithVariadicArgumentMethod|MockObject $mock */