我试图为我的表单编写一些测试,以确认验证器在需要时检索预期的错误。表单只有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中生成一个错误的验证?这是验证器中的错误还是我遗漏了什么?
另外:
有没有更好的方法来测试表单验证器?
2-是否存在与assertSessionHasErrors()相反的断言来检查某个错误,是否抛出了而不是?
发布于 2018-10-10 17:42:30
如果在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控制台中。
https://stackoverflow.com/questions/47850238
复制相似问题