PHPunit testing I writing phpunit tests for Lumen API, and for some reason framework doesn't use .env.testing configuration file for the test database.
As from Laravel 5.5 - Laravel 5.7, I used to create .env.testing file to run test seeders and phpunit tests.
.env
APP_ENV=local
APP_DEBUG=true
APP_KEY=appkey
APP_TIMEZONE=UTC
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=api
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=file
QUEUE_DRIVER=sync
.env.testing
APP_ENV=testing
APP_DEBUG=true
APP_KEY=appkey
APP_TIMEZONE=UTC
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=api_test
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=file
QUEUE_DRIVER=sync
phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="bootstrap/app.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Application Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
</php>
</phpunit>
I normally just set the ENV variables in phpunit.xml e.g.
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_DATABASE" value="api_test"/>
</php>
yes, this way phpunit test works only if test database has tables migrated, but I need to migrate and seed test data to api_test. when using following commands. original database is being target.
artisan migrate --env="testing"
artisan db:seed --env="testing"
You can specify a database connection using if you have a separate database configured in your config\database.php
--database[=DATABASE] The database connection to use
To be honest I normally just use an in-memory database with
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
Then use use RefreshDatabase; in my tests. Works like a charm
Agree, but using sqlite in phpunit.xml make no effect on database migrations & seeding for --env="testing"
even though I specify DB_CONNECTION & DB_DATABASE in phpunit.xml, how does artisan know which database target?
The RefreshDatabase trait handles running the migrations on the configured database
Please sign in or create an account to participate in this conversation.