I have a trait with a helper that looks like this
trait CliHelpers
{
public static function cliError(string $errorMessage): void
{
try {
\WP_CLI::error($errorMessage);
} catch (ExitException $exception) {
self::terminate($exception);
}
}
public static function terminate(ExitException $exception)
{
exit("{$exception->getCode()}: {$exception->getMessage()}");
}
}
I've added a public static method terminate so that I can test this part of the branch, without the test killing my PHP execution (because of the exit). The WP_CLI part will be mocked to throw the exception (this part works).
I'm using Pest for my unit testing framework.
My test looks like this
<?php
namespace Tests\Unit\Cli;
use EightshiftLibs\Cli\CliHelpers;
use WP_CLI\ExitException;
/**
* Mock before tests.
*/
beforeEach(function () {
$wpCliMock = \Mockery::mock('alias:WP_CLI');
$wpCliMock
->shouldReceive('error')
->andReturnUsing(function ($message) {
throw new ExitException($message);
});
});
/**
* Cleanup after tests.
*/
afterEach(function () {
\Mockery::close();
});
test('CliError helper will catch the exit', function() {
$this->expectException(\Exception::class);
$mock = \Mockery::mock(CliHelpers::class)
->shouldAllowMockingProtectedMethods()
->makePartial();
$mock->shouldReceive('terminate')
->andThrow(new \Exception);
$mock::cliError('Error message');
});
So first I mock the WP_CLI so that I throw the exception (I'm testing this part of the branch).
Then I am trying to override the terminate method, but for some reason, when I run the single test inside PHPStorm, I get
...
Testing started at 10:51 ...
PHPUnit 9.5.2 by Sebastian Bergmann and contributors.
Process finished with exit code 0
0: Error message
It actually goes to the exit method. And when I run the tests in the terminal, this test is never run ♂️
Is there a way to test this exiting part of the helper? I'm trying to avoid throwing another exception because then I'll have to put a bunch of throw/catch blocks through the entire codebase.