我正在尝试为我的表单编写一些测试,以确认验证程序在需要时检索预期的错误。
表单只有3个字段:name
,discount
和expiration
,验证程序如下所示:
$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()相反的断言,以检查某个错误 NOT 是否被抛出?
答案 0 :(得分:0)
如果您在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();
}
现在,错误和堆栈跟踪的完整输出将显示在PHPUnit控制台中。