繁体   English   中英

如何在测试POST请求时使用Laravel Input :: replace()

[英]How to use Laravel Input::replace() in testing POST requests

我在使用Laravel的Input::replace()方法在单元测试期间模拟POST请求时遇到了一些麻烦。

根据Jeffrey Way 这里这里的说法,你可以这样做:

# app/tests/controllers/PostsControllerTest.php

public function testStore()
{
    Input::replace($input = ['title' => 'My Title']);</p>

    $this->mock
         ->shouldReceive('create')
         ->once()
         ->with($input);

    $this->app->instance('Post', $this->mock);

    $this->call('POST', 'posts');

    $this->assertRedirectedToRoute('posts.index');
}

但是,我无法让这个工作。 在使用Input::replace()之后, Input::all()和所有Input::get()调用仍然返回一个空数组或null。

这是我的测试功能:

public function test_invalid_login()
{
    // Make login attempt with invalid credentials
    Input::replace($input = [
        'email'     => 'bad@email.com',
        'password'  => 'badpassword',
        'remember'  => true
    ]);

    $this->mock->shouldReceive('logAttempt')
    ->once()
    ->with($input)
    ->andReturn(false);

    $this->action('POST', 'SessionsController@postLogin');

    // Should redirect back to login form with old input
    $this->assertHasOldInput();
    $this->assertRedirectedToAction('SessionsController@getLogin');
}

$this->mock->shouldReceive()不会被$input调用 - 它只获得一个空数组。 我已经在调试器中通过查看每个值的Input::all()Input::get()来确认这一点,并且它们都是空的。

TL / DR:如何在Laravel单元测试中发送带有POST数据的请求?

您应该使用Request::replace() ,而不是Input::replace来替换当前请求的输入数据。

暂无
暂无

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

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