LoginSignup
0
0

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-08-30

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>    
.env.testing
APP_ENV=test
APP_KEY=[YOURKEY]
APP_DEBUG=true 
$ php artisan:migrate database=mysql_testing
$ ./vendor/bin/phpunit
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0