Skip to content

Instantly share code, notes, and snippets.

@IceTimux

IceTimux/3f995.md

Last active Dec 12, 2020
Embed
What would you like to do?

~Laravel ~Fix | How to fix Call to a member function connection() on null error on Laravel >=6.x


I decided to spin up a fresh Laravel 8 installation to do some practicing on. I noticed that if you run php artisan test all tests pass out of the box. This is a little strange to me, I feel that you should start with a failing test. So I decided to go into the example unit test and modify it so it will NOT PASS!

My idea was simple, I am going to pull in the User model and assert that there should be 1 user there. This test should not pass. I did however run the migrations.

But if you try and modify one of the example tests to include one of your models you will notice something strange.

consider the following example using the supplied example unit test from Laravel 8.

<?php

namespace Tests\Unit;

// pull in user model
use App\Models\User;
use PHPUnit\Framework\TestCase;

class ExampleTest extends TestCase
{
    // add a property to keep track of the users count
    private $usersCount;

    // add a setup method
    public function setUp() :void
    {
        // call the parent setup
        parent::setUp();
        // assign the users count
        $this->usersCount = User::all()->count();
    }

    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        // assert that there is 1 user
        $this->assertEquals(1, $this->usersCount);
        $this->assertTrue(true);
    }
}

In this example we have included our User model, added a setUp method for the test case and fetched the amount of users from the database.

If we run our tests now we will get the following error message.

• Tests\Unit\ExampleTest > basic test
   Error 

  Call to a member function connection() on null

It turns out that the TestCase we are inheriting from is from is being supplied by PHPUnit\Framework. In order for the error to go away we have to make sure we are inheriting from Tests\TestCase.

The fix is simple, just replace your use PHPUnit\Framework\TestCase; statement with use Tests\TestCase;.

When we run the tests now it should fail with the error we are expecting

• Tests\Unit\ExampleTest > basic test
  Failed asserting that 0 matches expected 1.

Apparently this has been a problem since Laravel 6.


Sources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment