2016-05-31 67 views
1

我是一個新手開發人員,我試圖讓phpUnit成立,並在現有的應用程序中設置了一個基本的測試套件,但我沒有發展。我正在瀏覽laravel文檔並試圖運行一些基本的測試。當我嘗試運行以下命令:測試phpUnit路由時出錯:ErrorException:試圖獲取非對象的屬性

$response = $this->action('GET', '[email protected]'); 

我得到以下異常:

AlertsControllerTest::testIndexRoute 
ErrorException: Trying to get property of non-object 

我打電話的方法是:

public function count() { 
    $statusIds = DB::table('alert_status')->where('user_id', $this->crmUser->id)->where('is_new', 0)->lists('alert_id'); 
    $count = DB::table('alerts')->WhereNotIn('id', $statusIds)->count(); 
    return Response::json($count); 
} 

有誰知道我爲什麼得到這個錯誤?據我所知,我並沒有試圖獲得任何東西的屬性。我只是想調用路線。

的測試方法引發錯誤是:

public function testIndexRoute() { 
     $this->crmUser = new stdClass(); 
     $this->crmUser->id = new stdClass(); 
     $this->crmUser->id = 1; 
     $response = $this->action('GET','[email protected]');   
     $count = $response->original; $this->assertResponseOk(); 
    } 

回答

1

隨着職位的非常有限的信息,我猜問題是$this->crmUser->id。在計數方法中調用數據庫之前,請嘗試執行crmUservar_dump

我猜你的單元測試沒有爲正在測試的count()方法所屬的類的實例設置crmUser。

public function count() { 
     var_dump($this->crmUser); 
     $statusIds = DB::table('alert_status')->where('user_id', $this->crmUser->id)->where('is_new', 0)->lists('alert_id'); 
     $count = DB::table('alerts')->WhereNotIn('id', $statusIds)->count(); 
     return Response::json($count); 
} 

如果您發佈了您的phpunit測試方法的文本,這將有很大的幫助。

+0

我仍然得到儘管同樣的錯誤...... 公共職能testIndexRoute(){ $這個 - > crmUser =新stdClass的(); $ this-> crmUser-> id = new stdClass(); $ this-> crmUser-> id = 1; $ response = $ this-> action('GET','AlertsController @ bannerAlerts'); $ count = $ response-> original; $ this-> assertResponseOk(); } – brianfr82

+0

@ brianfr82我將測試方法添加到OP中。你的問題是你現在在測試方法裏面添加'$ this-> crmUser',把它添加到'AlertsControllerTest'中,而不是被測試的類。你需要注入用戶到被測試的類,'AlertsController'的實例' – Ray

+0

我遵循你所說的話,但我不知道如何在php中真正做到這一點。你能否更深入地解釋一下?對不起,我很沒經驗,我有很多事情要拋給我。 – brianfr82

相關問題