簡體   English   中英

Laravel 5.5 PHPUnit測試表單驗證

[英]Laravel 5.5 phpunit testing form validation

我正在嘗試為表單編寫一些測試,以確認驗證程序在需要時檢索到預期的錯誤。 該表單僅包含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:yesterday規則,使驗證者如下所示:

$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的相反()來檢查一個特定的誤差被扔?

如果您在PHPUnit中看到此類錯誤: Failed asserting that false is true. ,您可以將'disableExceptionHandling'函數添加到tests/TestCase.php

<?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();
    }

現在,錯誤和stacktrace的完整輸出將顯示在PHPUnit控制台中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM