代码之家  ›  专栏  ›  技术社区  ›  Rey Young

phpunit:Laravel中存在验证异常

  •  0
  • Rey Young  · 技术社区  · 7 年前

    我已经转身了 throw Exception 在里面 handler.php 以便我能抓住 exceptions 然后看看 errors 但当我尝试 validation checks 它向我抛出了一个正确的异常,但在我的测试用例中,它没有捕获 exception 我断言会话有错误。

    /** @test*/
        public function a_thread_requires_a_title(){
    
            $thread = make('App\Thread', ['title'=> null]);
            $this->post('threads', $thread->toArray())
                ->assertSessionHasErrors('title');
        }
    

    既然, validation error 是一个异常,因此它引发了一个异常,因为我修改了 处理程序.php 文件为

    if(app()->environment() === "testing") throw $exception;
    

    所以,我要做的是改变这个测试的env,这样它就不会给我一个“异常”。

    0 回复  |  直到 7 年前
        1
  •  1
  •   senty    7 年前

    您可以在测试方法的顶部编写两个助手方法:

    $this->withoutExceptionHandling(); $this->withExceptionHandling();

    它们包含在Laravel的“Lealth\\基金会\测试\关注\交互异常处理”中,这是您应该从测试中扩展的抽象测试用例所使用的。 ( as mentioned here )

    /** @test*/
    public function a_thread_requires_a_title() {
        $this->withExceptionHandling();
    
        $thread = make('App\Thread', ['title'=> null]);
        $this->post('threads', $thread->toArray())
            ->assertSessionHasErrors('title');
    }
    
    推荐文章