laravelunit-testingphpunitlumenlaravel-testing

How to test Laravel/Lumen API when retrieving the logged in user's ID in controller constructor?


I'm trying to test CRUD operations for my Lumen controllers. The constructor for each controller looks similar to this:

  private $loggedInUserId;

  public function __construct(Request $request) {
      $this->loggedInUserId = $request->user()->userId;
  }

And here's my test:

  public function testShowOneItemReturnsOnePayroll() {
    $this->withoutMiddleware();
    $this->json('GET', "intranet");
    $this->seeJsonStructure([
      'data' => [
        'prId',
        'userId',
        'firstName',
        'lastName',
        ...
      ]
    ]);
  }

I get this error when running the test:

PHPUnit\Framework\InvalidArgumentException: Argument #2 of PHPUnit\Framework\Assert::assertArrayHasKey() must be an array or ArrayAccess

However, The test is successful when I comment out the $loggedInUserId variable and its constructor initialization.

Question

How can I retrieve the user ID in my controllers and still get my tests to pass?


Solution

  • I solved my problem in part thanks to hotsaucejake in this Laracasts post.

    I created a UserFactory and used it to create a "fake" User model, and referenced it using actingAs():

      public function testShowAllItemsReturnsAllPayrollRecords() {
        $user = UserFactory::new()->create();
        $this->withoutMiddleware();
        $this->actingAs($user)->json('GET', 'intranet');
        ...
    }