【问题标题】:Error in testing phpUnit route: ErrorException: Trying to get property of non-object测试 phpUnit 路由时出错:ErrorException: Trying to get property of non-object
【发布时间】:2026-01-22 16:50:01
【问题描述】:

我是一名新手开发人员,我正在尝试在我未开发的现有应用程序中设置 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(); 
    } 

【问题讨论】:

    标签: php laravel phpunit


    【解决方案1】:

    由于帖子中的信息非常有限,我猜问题是$this->crmUser->id。在 count 方法中调用 DB 之前,请尝试对 crmUser 执行 var_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 测试方法的文本,这将有很大帮助。

    【讨论】:

    • 我仍然遇到同样的错误... public function testIndexRoute() { $this->crmUser = new stdClass(); $this->crmUser->id = new stdClass(); $this->crmUser->id = 1; $response = $this->action('GET', 'AlertsController@bannerAlerts'); $count = $response->原始; $this->assertResponseOk(); }
    • @brianfr82 我将您的测试方法添加到了 OP。您的问题是您现在在测试方法中添加$this->crmUser 将其添加到AlertsControllerTest,而不是正在测试的类。您需要将用户注入到被测试的类中,AlertsController的实例
    • 我按照你所说的但我不确定如何在 php 中实际执行它。你能更深入地解释一下吗?抱歉,可悲的是,我缺乏经验,而且我遇到了很多问题。
    • AlertsControllerTest 类扩展了什么?
    • 一个 BaseController 类。它的构造函数设置 crmUser
    最近更新 更多