G
G
gigisarri982022-02-09 12:54:05
Laravel
gigisarri98, 2022-02-09 12:54:05

Why is Laravel not connecting to the DB during testing?

I am writing unit tests for a Laravel application. Everything was fine until we got to the database. As soon as any model in the method under test is affected, an error occurs:

Error: Call to a member function connection() on null
// и тут вывод десятка строк из базового класса моделей Laravel

The probability that the problem is not in the method under test tends to 100 percent, because this error propagates to all such methods.
Lines from .env with database connection:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=parser
DB_USERNAME=root
DB_PASSWORD=1111

phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
>
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <coverage processUncoveredFiles="true">
        <include>
            <directory suffix=".php">./app</directory>
        </include>
    </coverage>
    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <!-- <server name="DB_CONNECTION" value="sqlite"/> -->
        <!-- <server name="DB_DATABASE" value=":memory:"/> -->
        <server name="MAIL_MAILER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
        <server name="TELESCOPE_ENABLED" value="false"/>
        <env name="DB_CONNECTION" value="mysql"/>
        <env name="DB_HOST" value="127.0.0.1"/>
        <env name="DB_PORT" value="3306"/>
        <env name="DB_DATABASE" value="parser"/>
        <env name="DB_USERNAME" value="root"/>
        <env name="DB_PASSWORD" value="1111"/>
    </php>
</phpunit>


What I did:
1.Changed the class that extends the test from PHPUnit\Framework\TestCase to Tests\TestCase.
2.As you can see above, I added env to phpunit.xml. Yes, the environment sees them and they are displayed in var_dump().
3. Changed the environment to local (yes, I cleared the cache).

The result is the same, Google does not help, please help, I don’t know what to do.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2022-02-09
@gigisarri98

All that can be said is that the “cannot connect to the database” error looks different.
You have it in something else.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question