PHPUnit 断言项目

PHPUnit Assertions project

我正在开发一个 PHP 项目,该项目需要验证对预定义模式的 JSON 请求,该模式可在 swagger 中使用。现在我完成了研究,发现最好的项目是 SwaggerAssertions:

https://github.com/Maks3w/SwaggerAssertions

在 SwaggerAssertions/tests/PhpUnit/AssertsTraitTest.php 中,我很乐意使用 testAssertRequestBodyMatch 方法,您可以在其中执行此操作:

self::assertRequestBodyMatch($request, $this->schemaManager, '/api/pets', 'post');

上面的断言完全符合我的需要,但是如果我传递一个无效的请求,它会导致致命错误。我想捕获它并处理返回的响应,而不是完全退出应用程序。

我如何利用这个项目,即使它看起来像是 PHPUnit 的全部?我不太确定如何在正常的 PHP 生产代码中使用这个项目。任何帮助将不胜感激。

如果不满足条件,断言会抛出异常。如果抛出异常,它将停止执行所有后续代码,直到它被 try catch 块捕获。未捕获的异常将导致致命错误,程序将退出。

要防止您的应用程序崩溃,您需要做的就是处理异常:

try {
    self::assertRequestBodyMatch($request, $this->schemaManager, '/api/pets', 'post');

    // Anything here will only be executed if the assertion passed

} catch (\Exception $e) {
    // This will be executed if the assertion,
    // or any other statement in the try block failed

    // You should check the exception and handle it accordingly
    if ($e instanceof \PHPUnit_Framework_ExpectationFailedException) {
        // Do something if the assertion failed
    }

    // If you don't recognise the exception, re-throw it
    throw $e;
}

希望对您有所帮助。