danilopolani/laravel-json-validation-testing

更好的 JSON 验证错误测试

v2.0.0 2024-03-10 18:02 UTC

This package is auto-updated.

Last update: 2024-09-29 05:09:06 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

一个简单的库,帮助通过规则测试 JSON 验证错误。

目前测试 HTTP 错误的方法是 有缺陷的:它测试验证是否失败或者你必须手动指定错误消息。使用此包,你只需指定失败的验证规则,它就会构建出错误消息,确保 100% 会失败以及 是什么原因失败。(进一步阅读 这里 有关 Laravel 旧合并请求的更多信息)。

安装

您可以通过 composer 安装此包

composer require --dev danilopolani/laravel-json-validation-testing

用法

该包提供了一种辅助工具,用于检索编译后的错误消息

use DaniloPolani\JsonValidation\JsonValidation;

JsonValidation::getRuleErrorMessage('foo', 'required');

// => ["The foo field is required."]

然而,如果您需要测试您的 HTTP API,该包包含一个全新的 assertJsonValidationErrorRule 断言,以使您的生活更加轻松

it('throws validation error', function () {
    $this->postJson('/')
        ->assertJsonValidationErrorRule('foo', 'required');
});

它还支持动态规则,如 betweensizemax 等。您只需指定要应用的规则类型即可

it('throws validation error', function () {
    $this->postJson('/')
        ->assertJsonValidationErrorRule('foo', 'between.string:1,5') // The foo must be between 1 and 5 characters.
        ->assertJsonValidationErrorRule('foo', 'size.array:3'); // The foo must contain 3 items.
});

您甚至可以通过提供 field => rule 的数组作为参数,一次性测试多个验证错误

use DaniloPolani\JsonValidation\JsonValidation;

it('throws validation error', function () {
    $this->postJson('/')
        ->assertJsonValidationErrorRule([
            'foo' => 'required',
            'bar' => 'required_array_keys:foo,baz',
        ]);
});

自定义规则

如果您想测试自定义规则,请确保它实现了接口 DaniloPolani\JsonValidation\Contracts\HasRuleMessage,这是提取失败消息以进行检查所需的。

例如,一个自定义规则看起来像这样

<?php
 
namespace App\Rules;
 
use Closure;
use DaniloPolani\JsonValidation\Contracts\HasRuleMessage;
use Illuminate\Contracts\Validation\ValidationRule;
 
class Uppercase implements ValidationRule, HasRuleMessage
{
    /**
     * Run the validation rule.
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (strtoupper($value) !== $value) {
            $fail($this->message());
        }
    }

    public function message(): string
    {
        return 'The :attribute must be uppercase.';
    }
}

然后您可以在断言函数中使用它

当然,您也可以提供自己的自定义验证规则

it('throws validation error', function () {
    $this->postJson('/')
        ->assertJsonValidationErrorRule('foo', new Uppercase());
});

测试

composer test

更新日志

请参阅 更新日志 了解最近更改的详细信息。

贡献

请参阅 贡献指南 了解详细信息。

安全漏洞

请查看 我们的安全策略 了解如何报告安全漏洞。

致谢

许可证

MIT 许可证 (MIT)。请参阅 许可证文件 了解更多信息。