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

时间:2014-06-05 02:51:42

标签: php unit-testing laravel http-post

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

根据Jeffrey Way herehere,您可以这样做:

# 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::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');
}

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

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

1 个答案:

答案 0 :(得分:8)

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