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

gla*_*ree 9 php unit-testing http-post laravel

我在使用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');
}
Run Code Online (Sandbox Code Playgroud)

但是,我不能让这个工作.Input::all()并且所有Input::get()调用仍然返回一个空数组或Input::replace()使用后返回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');
}
Run Code Online (Sandbox Code Playgroud)

$this->mock->shouldReceive()没有得到调用$input,但-它只是变得空数组.我通过查看Input::all()Input::get()查看每个值在调试器中确认了这一点,并且它们都是空的.

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

Vla*_*sny 8

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