brianfr82 brianfr82 - 6 months ago 80
PHP Question

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

I'm a novice developer and I'm trying to get phpUnit set up and a rudimentary testing suite set up in an existing app that I did not develop. I'm going through the laravel docs and trying to get some basic tests run. When I try to run the following:

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


I get the following exception:

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


The method I'm calling is:

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);
}


Does anyone know why I'm getting this error? To my knowledge, I'm not trying to get properties of anything. I'm just trying to call the route.

The test method throwing the error is:

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();
}

Ray Ray
Answer

With the very limited info in the post, I'm guessing the issue is $this->crmUser->id. Before you call the DB in the count method try to do a var_dump of the crmUser.

I'm guessing your unit test didn't setup a crmUser for the instance of the class which the count() method being tested belongs to.

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);
 }

It would help a great deal if you posted the text of your phpunit test method.

Comments