PHPUnit Mock exception

I have a class that handles errors, including exceptions. If an exception is caught, I will pass the exception as an argument to my exception / error handler.

try {
    someTrowingFnc();
} catch (\Exception $e) {
    this->error->exception($e);
}

Now I want a unit test handler for this error and make fun of the exception.

It's hard for me to mock this exception so that I can manage the message, file, and exception line.

$exceptionMock = $this->getMock('Exception', array(
    'getFile',
    'getLine',
    'getMessage',
    'getTrace'
)); // Tried all mock arguments like disable callOriginalConstructor

$exceptionMock->expects($this->any())
    ->method('getFile')
    ->willReturn('/file/name');

$exceptionMock->expects($this->any())
    ->method('getLine')
    ->willReturn('3069');

$exceptionMock->expects($this->any())
    ->method('getMessage')
    ->willReturn('Error test');

The results below always return NULL.

$file   = $exception->getFile();
$line   = $exception->getLine();
$msg    = $exception->getMessage();

Is there a way around the exceptions, or am I just doing something wrong?

+4
source share
2 answers

, , getFile() .., / final. PHPUnit , , .

Limitations
Please note that final, private and static methods cannot be stubbed or mocked. They are ignored by PHPUnit test double functionality and retain their original behavior.

: https://phpunit.de/manual/current/en/test-doubles.html

+5

, - :

/**
 * @param object $object        The object to update
 * @param string $attributeName The attribute to change
 * @param mixed  $value         The value to change it to
 */
protected function setObjectAttribute($object, $attributeName, $value)
{
    $reflection = new \ReflectionObject($object);
    $property = $reflection->getProperty($attributeName);
    $property->setAccessible(true);
    $property->setValue($object, $value);
}

.

$exception = $this->getMock('Exception');
$this->setObjectAttribute($exception, 'file',    '/file/name');
$this->setObjectAttribute($exception, 'line',    3069);
$this->setObjectAttribute($exception, 'message', 'Error test');

, , , . , , $this->any(), , .

, , , , , (, )

0

All Articles