2

我正在开发一个 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 生产代码中使用这个项目。任何帮助将不胜感激。

4

1 回答 1

1

如果条件不满足,断言会抛出异常。如果抛出异常,它将停止执行所有后续代码,直到它被捕获在一个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;
}

希望这可以帮助。

于 2016-05-18T13:34:15.383 回答