Using another database for phpunit test on Laravel 6 with docker-compose.

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

  1. Adding test database on docker-compose
  2. Adding setting for test database in config/database.php
  3. Adding environment at phpunit.xml
  4. Create .env.testing as new env file
  5. Running migration command for test database
  6. 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>    

php:.env.testing


APP_ENV=test
APP_KEY=[YOURKEY]
APP_DEBUG=true 
$ php artisan:migrate database=mysql_testing
$ ./vendor/bin/phpunit

Recommended Posts

Using another database for phpunit test on Laravel 6 with docker-compose.
Test New Database System for Clustering Database on Containers
Create Laravel environment with Docker (docker-compose)
Notes for using BLE with iOS apps
[Ruby on Rails] View test with RSpec
Using JupyterLab + Java with WSL on Windows 10
Notes on using FCM with Ruby on Rails
[Ruby on Rails] Controller test with RSpec
[Ruby on Rails] Model test with RSpec
rails test fails with database reference error
Using Material Design for Bootstrap with Rails 5.2