测试 phpUnit 路由时出错:ErrorException:尝试获取非对象的 属性

Error in testing phpUnit route: ErrorException: Trying to get property of non-object

我是新手开发人员,我正在尝试设置 phpUnit 并在我未开发的现有应用程序中设置基本测试套件。我正在浏览 laravel 文档并尝试进行一些基本测试 运行。当我尝试 运行 以下内容时:

$response = $this->action('GET', 'AlertsController@bannerAlerts');

我得到以下异常:

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','AlertsController@bannerAlerts');           
       $count = $response->original; $this->assertResponseOk(); 
    } 

由于 post 中的信息非常有限,我猜测问题出在 $this->crmUser->id。在用计数方法调用数据库之前,请尝试执行 crmUservar_dump

我猜你的单元测试没有为正在测试的 count() 方法所属的 class 实例设置 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);
 }

如果您post编辑了您的 phpunit 测试方法的文本,将会有很大帮助。