【问题标题】:Laravel 5.5 phpunit testing form validationLaravel 5.5 phpunit 测试表单验证
【发布时间】:2018-05-30 17:17:02
【问题描述】:

我正在尝试为我的表单编写一些测试,以确认验证器在需要时检索到预期的错误。 该表单只有 3 个字段:namediscountexpiration,验证器如下所示:

$this->validate($request, [
    'name'          => 'required',
    'discount'      => 'required|numeric|between:1,100',
    'expiration'    => 'required|date_format:d/m/Y',
]);

在提交表单和使用 phpunit 使用以下代码运行测试时都可以正常工作:

/**
 * Discount must be numeric check
 */
$response = $this->post(route('offer.create'), [
    'name'          => $faker->sentence(4),
    'discount'      => 'asdasd',
    'expiration'    => $faker->dateTimeBetween('+1 days', '+5 months')
]);

// Check errors returned
$response->assertSessionHasErrors(['discount']);

由于折扣不是数字,它会引发预期的错误,每个人都很高兴。

现在,如果我想添加一条新规则以确保到期时间等于或大于今天,我添加 after:yesterdayrule 留下验证器,例如:

$this->validate($request, [
    'name'          => 'required',
    'discount'      => 'required|numeric|between:1,100',
    'expiration'    => 'required|date_format:d/m/Y|after:yesterday',
]);

提交表单时效果很好。我收到错误消息说折扣不是数字,但是在使用 phpunit 进行测试时,它没有得到预期的错误:

1) Tests\Feature\CreateSpecialOfferTest::testCreateSpecialOffer
Session missing error: expiration
Failed asserting that false is true.

为什么将这个新的验证规则添加到 expiration 会在 discount 中生成错误验证?这是验证器中的错误还是我遗漏了什么?

还有:

1 - 有没有更好的方法来测试表单验证器?

2 - 是否有一个与 assertSessionHasErrors() 相反的断言来检查某个错误是否被抛出?

【问题讨论】:

标签: php forms validation phpunit laravel-5.5


【解决方案1】:

如果您在 PHPUnit 中看到这种错误:Failed asserting that false is true.,您可以在tests/TestCase.php 中添加 'disableExceptionHandling' 函数:

<?php

namespace Tests;

use Exception;
use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected function disableExceptionHandling()
    {
        // Disable Laravel's default exception handling
        // and allow exceptions to bubble up the stack
        $this->app->instance(ExceptionHandler::class, new class extends Handler {
            public function __construct() {}
            public function report(Exception $exception) {}
            public function render($request, Exception $exception)
            {
                throw $exception;
            }
        });
    }
}

在你的测试中你这样称呼它:

    <?php    
    /** @test */
    public function your_test_function()
    {

        $this->disableExceptionHandling();
    }

现在,错误和堆栈跟踪的完整输出将显示在 PHPUnit 控制台中。

【讨论】:

  • 注意:在 Laravel 的更高版本中,您可以使用 $this->withoutExceptionHandling() 而不编写任何代码。
猜你喜欢
  • 2018-03-11
  • 2018-03-09
  • 2020-02-19
  • 2017-05-23
  • 1970-01-01
  • 2018-06-30
  • 2018-09-05
  • 2019-09-10
  • 2018-12-17
相关资源
最近更新 更多