respect-validation/tests/feature/ValidationExceptionStackTraceTest.php
Henrique Moody 75a9b8e94f
Overwrite file and line in ValidationException
Because of how PHP works, when we instantiate an Exception object, the
`file` and `line` properties are the file and line where we created the
object. That's a desirable behaviour, but there's no value for a user to
know that we created an instance of `ValidationException` in the
`Validator` class.

This commit will overwrite the file and line in the
`ValidationException` to where the method `assert()` was called.

Note that when running `check()` it will still point to `Validator`, but
I decided not to change it, as the method `check()` got deprecated.
2024-12-18 19:49:09 +01:00

28 lines
790 B
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
use Respect\Validation\Exceptions\ValidationException;
test('Should overwrite stack trace when in Validator', function (): void {
try {
v::intType()->assert('string');
} catch (ValidationException $e) {
expect($e->getFile())->toBe(__FILE__);
expect($e->getLine())->toBe(__LINE__ - 3);
}
});
test('Should not overwrite stack trace when created manually', function (): void {
try {
throw new ValidationException('message', 'fullMessage', ['id' => 'message']);
} catch (ValidationException $e) {
expect($e->getFile())->toBe(__FILE__);
expect($e->getLine())->toBe(__LINE__ - 3);
}
});