Every engineer would hope to divide database when running test.
I'll show using another database for phpunit test on Laravel 6 with docker-compose in this article.
STEP
- Adding test database on docker-compose
- Adding setting for test database in config/database.php
- Adding environment at phpunit.xml
- Create .env.testing as new env file
- Running migration command for test database
- Running phpunit
CODES
docer-compose.yml
version: '3'
services:
db:
build:
context: ./app/mysql
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: hoge
MYSQL_USER: hoge
MYSQL_PASSWORD: hoge
container_name: mydb
ports:
- "3306:3306"
tty: true
volumes:
- ./app/mysql/db_data:/var/lib/mysql
testdb:
build:
context: ./app/mysql
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: hoge
MYSQL_USER: hoge
MYSQL_PASSWORD: hoge
container_name: testdb
ports:
- "3307:3306"
tty: true
volumes:
- ./app/mysql/testdb_data:/var/lib/mysql
web:
...
config/database.php
...
'connections' => [
...
'mysql' => [
...
],
'mysql_testing' => [
...
'host' => 'testdb',
...
],
phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
...
<php>
<env name="APP_ENV" value="testing" force="true"/>
<env name="DB_CONNECTION" value="mysql_testing" force="true"/>
...
</php>
</phpunit>
.env.testing
APP_ENV=test
APP_KEY=[YOURKEY]
APP_DEBUG=true
$ php artisan:migrate database=mysql_testing
$ ./vendor/bin/phpunit