2014-02-05 66 views
5

運行我的單元測試時出現以下錯誤。似乎它不喜歡將Input :: get傳遞給構造函數,但是當在瀏覽器中運行腳本時,該操作正常工作,所以我知道它不是控制器代碼。如果我取出任何'task_update'代碼,測試只是通過輸入發現 - 因此不確定爲什麼它接受一種方法的輸入。Laravel - 輸入不通過單元測試

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

我相信「調用」函數吹走了Input :: replace所做的工作。

調用函數實際上可以帶一個$ parameters參數,它可以解決您的問題。

,如果你在\照亮\基金會\測試\的TestCase看@呼叫時,您會看到功能:

/** 
* 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')); 

,我認爲它應該工作。

1

我不喜歡做既Input::replace($input)$this->call('POST', 'path', $input)

例AuthControllerTest.php:

public function testStoreSuccess() 
{ 
    $input = array(
     'email' => '[email protected]', 
     '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 

}