0

我想知道是否可以通过方法JsonType为验证 API 响应定义一些自定义。seeResponseMatchesJsonType我的意思是,假设我有一个结构的响应:

[
   'id' => 'integer',
   'name' => 'string',
   'address' => [
      'street' => 'string',
      'city' => 'string'
   ]
]

显然这个结构address嵌入了复杂的类型,并且在整个应用程序中这种类型可能会被多次使用,所以我想简单地写:

$I->seeResponseMatchesJsonType([
   'id' => 'integer',
   'name' => 'string',
   'address' => 'addressType'
]);

无需一直重写这个嵌入式结构。如何在 Codeception 中实现它?

4

1 回答 1

1

是的,您可以使用 \Codeception\Util\JsonType 类中的方法 addCustomFilter 来做到这一点。

/**
     * Adds custom filter to JsonType list.
     * You should specify a name and parameters of a filter.
     *
     * Example:
     *
     * ```php
     * <?php
     * JsonType::addCustomFilter('email', function($value) {
     *     return strpos('@', $value) !== false;
     * });
     * // => use it as 'string:email'

     *
     * // add custom function to matcher with `len($val)` syntax
     * // parameter matching patterns should be valid regex and start with `/` char
     * JsonType::addCustomFilter('/len\((.*?)\)/', function($value, $len) {
     *   return strlen($value) == $len;
     * });
     * // use it as 'string:len(5)'
     * ?>
     * ```
     *
     * @param $name
     * @param callable $callable
     */
    public static function addCustomFilter($name, callable $callable)
    {
        static::$customFilters[$name] = $callable;
    }
于 2017-08-23T06:42:23.227 回答