简体   繁体   English

Laravel单元测试assertRedirectedTo

[英]Laravel unit testing assertRedirectedTo

I am working with some unit testing and i have difficult with one kind of assertions 我正在进行一些单元测试,我对一种断言很困难

  $this->assertRedirectedTo

Here is my very basic example controller code 这是我的基本示例控制器代码

        // example.com/form
        public function postForm()
        {
            $data = "my data";
            $this->mylogic($data);
        }
        private function mylogic($data){
            // operations with $data ... after some logics
            return redirect()
                ->route('Gracias')
                ->send();
        }

And this is my very basic example of my unit testing 这是我单元测试的基本示例

        public function REDRIRECT_TEST()
        {
            $this->call('POST','form'); // it works
            $this->assertRedirectedTo('gracias'); // it fails
        }

and I get this error 我收到这个错误

        Failed asserting that Illuminate\Http\Response Object (...) is an instance of class "Illuminate\Http\RedirectResponse".

This error happen when i use redirect inside another method 当我在另一个方法中使用重定向时发生此错误

    private function mylogic($data){
        return redirect()
            ->route('Gracias')
            ->send();
    }

Any idea how to deal with assertRedirectedTo where the redirect() is inside another method? 任何想法如何处理assertRedirectedTo redirect()在另一个方法内?

Edited . 编辑 Well, i re-thinked everythink and divided the logic from controller, now the logic is in another class and only return the correct route to redirect to the controller and my unit test pass. 好吧,我重新思考Everythink并将逻辑与控制器分开,现在逻辑在另一个类中,只返回正确的路由重定向到控制器和我的单元测试通过。

In laravel 5.7+ the methods are a little changed for the unit test. 在laravel 5.7+中,单元测试的方法略有改变。

        Session::start();
        $response = $this->call('POST', 'form', [
            '_token' => \Session::token(),
            'var' => 'value',
        ]);
        $response->assertStatus(302);
        $response->assertRedirect('gracias');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM