So I'm trying to write unit tests for a Laravel application like this:
protected function setUp()
{
parent::setUp();
$this->disableMiddlewareForAllTests();
$this->withoutExceptionHandling();
}
public function test_login_badRequest()
{
$response = $this->call('post', '/login');
$response->assertOk();
$response->assertJson(['status' => 400]);
}
The above works fine, and gives this output:
Test 'Tests\Unit\LoginTest::test_login_badRequest' started
Test 'Tests\Unit\LoginTest::test_login_badRequest' ended
Time: 69 ms, Memory: 12.00MB
OK (1 test, 2 assertions)
But the next test is another story:
public function test_login_goodRequest()
{
$response = $this->call('post', '/login', [
'email' => '[email protected]',
'password' => 'P4ssw0rd'
]);
$response->assertOk();
$response->assertJson(['status' => 200]);
}
As soon as the test hits this line of code in the application:
/* Retrieve User associated with posted email address */
$user = $this->userModel
->where('email', $request->post('email'))
->get();
die('here');// <-- Happens in browser, does not happen in tests.
This is the error:
1) Tests\Unit\LoginTest::test_login_goodRequest
PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
/var/www/html/projects/laravel-template/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68 ...
I've been banging my head against this one for a few days, any ideas what's going on here, and how to get that die to print in the tests? Cheers.
-- Laradock, Docker, nginx, mysql, PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Apr 5 2018 08:53:57) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.2.4-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies
EDITED:
.env:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:Z+p6uA3G2DyCCFBXOPgrWwls1U6z/vi8Zi2r4eKHxEY=
APP_DEBUG=true
DEBUGBAR_ENABLED=true
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=sample_database
DB_USERNAME=root
DB_PASSWORD=root
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
docker-compose.ymland.env- Alex KarshinDB_HOSTin.envis the same as the mysql container name. They do not specifycontainer_namein their originaldocker-compose.yml, therefore docker could name your containers asapplication_mysqlor something. If you rundocker ps, you will see the container names. Also, make sure PHPUnit uses the same mysql container name when connecting, if it doesn't take the value from.env. - Alex Karshin