5

运行单元测试时,我收到以下错误。似乎它不喜欢将 Input::get 传递给构造函数,但是在浏览器中运行脚本时,该操作工作正常,所以我知道它不是控制器代码。如果我取出任何“task_update”代码,即使使用输入,测试也会通过 find - 所以不确定为什么它接受一种方法的输入。

ErrorException: Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, null given, called

我的控制器是:

public function store()
{
    $task_update = new TaskUpdate(Input::get('tasks_updates'));

    $task = $this->task->find(Input::get('tasks_updates')['task_id']);

    $output = $task->taskUpdate()->save($task_update);

    if (!!$output->id) {
        return Redirect::route('tasks.show', $output->task_id)
                        ->with('flash_task_update', 'Task has been updated');
    }
}

测试是 - 我正在为 task_updates 数组设置输入,但没有被拾取:

    Input::replace(['tasks_updates' => array('description' => 'Hello')]);

    $mockClass = $this->mock;
    $mockClass->task_id = 1;

    $this->mock->shouldReceive('save')
               ->once()
               ->andReturn($mockClass);

    $response = $this->call('POST', 'tasksUpdates');

    $this->assertRedirectedToRoute('tasks.show', 1);
    $this->assertSessionHas('flash_task_update');
4

2 回答 2

4

我相信“调用”功能正在摧毁 Input::replace 所做的工作。

call 函数实际上可以采用 $parameters 参数来解决您的问题。

如果你查看 \Illuminate\Foundation\Testing\TestCase@call,你会看到函数:

/**
 * Call the given URI and return the Response.
 *
 * @param  string  $method
 * @param  string  $uri
 * @param  array   $parameters
 * @param  array   $files
 * @param  array   $server
 * @param  string  $content
 * @param  bool    $changeHistory
 * @return \Illuminate\Http\Response
 */
public function call()
{
    call_user_func_array(array($this->client, 'request'), func_get_args());

    return $this->client->getResponse();
}

如果你这样做:

$response = $this->call('POST', 'tasksUpdates', array('your data here'));

我认为它应该工作。

于 2014-02-28T19:54:17.347 回答
1

我更喜欢同时做Input::replace($input)$this->call('POST', 'path', $input)

示例 AuthControllerTest.php:

public function testStoreSuccess()
{
    $input = array(
        'email' => 'email@gmail.com', 
        'password' => 'password',
        'remember' => true
        );

    // Input::replace($input) can be used for testing any method which      
    // directly gets the parameters from Input class
    Input::replace($input);



    // Here the Auth::attempt gets the parameters from Input class
    Auth::shouldReceive('attempt')
    ->with(     
            array(
                    'email' => Input::get('email'),
                    'password' => Input::get('password')
            ), 
            Input::get('remember'))
    ->once()
    ->andReturn(true);

    // guarantee we have passed $input data via call this route
    $response = $this->call('POST', 'api/v1/login', $input);
    $content = $response->getContent();
    $data = json_decode($response->getContent());

    //... assertions

}
于 2014-06-12T08:50:35.833 回答