我有一个看起来像这样的助手的特征
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()}");
}
}
我添加了一个公共静态方法 terminate
,以便我可以测试分支的这一部分,而不会因为测试而终止我的 PHP 执行(因为 exit
)。 WP_CLI
部分将被模拟以抛出异常(这部分有效)。
我的单元测试框架使用 Pest。
我的测试是这样的
<?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');
});
所以首先我模拟 WP_CLI
以便抛出异常(我正在测试分支的这一部分)。
然后我试图覆盖 terminate
方法,但由于某种原因,当我在 PHPStorm 中运行单个测试时,我得到
...
Testing started at 10:51 ...
PHPUnit 9.5.2 by Sebastian Bergmann and contributors.
Process finished with exit code 0
0: Error message
它实际上转到了退出方法。当我在终端中运行测试时,这个测试永远不会运行??♂️
有没有办法测试这个助手的退出部分?我试图避免抛出另一个异常,因为那样我将不得不在整个代码库中放置一堆 throw/catch 块。