Laravel 5 Unit Test - Call to a member function connection() on null

One more reason

check if the test class is extending use Tests\TestCase; rather then use PHPUnit\Framework\TestCase;

Laravel ships with the later, but Tests\TestCase class take care of setting up the application, otherwise models wont be able to communicate with the database if they are extending PHPunit\Framework\TestCase.


First of all, setUp() is called before every test, so you shouldn't call it from within the constructor

Second of all, you should call the parent::setUp() in your setUp() to initialize the app instance.


Example:

<?php

class ExampleTest extends TestCase
{
  private $user;

  public function setUp()
  {
    parent::setUp();

    $this->user = \App\User::first();
  }

   public function testExample()
   {
      $this->assertEquals('[email protected]', $this->user->email);
   }
}

a solution

use PHPunit\Framework\TestCase

Put this

use Tests\TestCase


You are assigning the id '2' to both shops.

Assigning is should not be neccessary since I assume the shop table id field is an autoincrement field.

Also look into database factories in the Laravel docs, it will simplify things for you.