首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel 5.5 phpunit测试表格验证

问Laravel 5.5 phpunit测试表格验证
EN

Stack Overflow用户
提问于 2017-12-16 21:44:49
回答 1查看 3.6K关注 0票数 1

我试图为我的表单编写一些测试,以确认验证器在需要时检索预期的错误。表单只有3个字段:name、discount和expiration,验证器如下所示:

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

这在提交表单和使用phpunit使用以下代码运行测试时都很好:

代码语言:javascript
复制
/**
 * 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:yesterday规则,使验证器保持如下所示:

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

在提交表单时,这样做很好。我得到的错误是,折扣不是数字,但是在用phpunit进行测试时,它不会像预期的那样得到错误:

代码语言:javascript
复制
1) Tests\Feature\CreateSpecialOfferTest::testCreateSpecialOffer
Session missing error: expiration
Failed asserting that false is true.

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

另外:

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

2-是否存在与assertSessionHasErrors()相反的断言来检查某个错误,是否抛出了而不是?

EN

回答 1

Stack Overflow用户

发布于 2018-10-10 17:42:30

如果在PHPUnit:Failed asserting that false is true.中看到此类错误,可以将“disableExceptionHandling”函数添加到tests/TestCase.php

代码语言:javascript
复制
<?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;
            }
        });
    }
}

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

代码语言:javascript
复制
    <?php    
    /** @test */
    public function your_test_function()
    {

        $this->disableExceptionHandling();
    }

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47850238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档