如何在Laravel中测试POST路由 [英] How to test POST routes in Laravel

查看:595
本文介绍了如何在Laravel中测试POST路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行以下操作,以测试对Laravel的POST调用.我希望根据我的路线将对问题的POST发送为存储操作方法.在浏览器中可以使用.

I'm doing the following to test a POST call to Laravel. I'm expecting that POST to questions, in accordance with my routes, will be dispatches as the store action method. This works in the browser.

我的测试:

public function setUp()
    {   
        parent::setUp();

        Session::start();
    }

    public function testStoreAction()
    {
        $response = $this->call('POST', 'questions', array(
            '_token' => csrf_token(),
        ));

        $this->assertRedirectedTo('questions');
    }

但是,我告诉我重定向不匹配.另外,我可以看到它根本不会使用store action方法.我想知道它要使用哪种操作方法,为什么不去使用store方法(如果我查看route:list,我可以看到有一个POST问题/应该转到questions.store的路由;这也可以在浏览器中使用,但不能在我的测试中使用).另外,我是否为此资源正确编写了呼叫?我在这里添加了令牌,因为它会抛出异常,在某些测试中,我会让令牌通过检查.

However, I tells me that the redirect doesn't match. Also, I can see that it isn't going to the store action method at all. I want to know what action method it is going to, and why it isn't going to the store method (if I look at route:list I can see there is a POST questions/ route that should go to questions.store; this also works in the browser, but not in my tests). Also, am I writing the call correctly for this resource? I added the token here as it was throwing an exception as it should, in some tests I will let the token check pass.

推荐答案

您可以尝试以下方法:

public function testStoreAction()
{
    Session::start();
    $response = $this->call('POST', 'questions', array(
        '_token' => csrf_token(),
    ));
    $this->assertEquals(302, $response->getStatusCode());
    $this->assertRedirectedTo('questions');
}

这篇关于如何在Laravel中测试POST路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆