我正在处理一个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;
}
希望这能有所帮助。