Skip to content

Instantly share code, notes, and snippets.

@iwyg
Last active April 16, 2019 15:51
Show Gist options
  • Save iwyg/9792105 to your computer and use it in GitHub Desktop.
Save iwyg/9792105 to your computer and use it in GitHub Desktop.
Mocking the database. Laravel Testing.
<?php
use \PDO;
use \Mockery as m;
use \Illuminate\Container\Container;
use \Illuminate\Database\DatabaseManager;
use \Illuminate\Database\Connectors\ConnectionFactory;
use \Illuminate\Database\Schema\Builder as SchemaBuilder;
trait DatabaseAwareTestTrait
{
protected $db;
protected $schema;
protected function prepareDatabase()
{
$config = [
'database.fetch' => PDO::FETCH_CLASS,
'database.default' => 'sqlite',
'database.connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]
]
];
$container = m::mock('Illuminate\Container\Container');
$container->shouldReceive('bound')->andReturn(false);
$container->shouldReceive('offsetGet')->with('config')->andReturn($config);
$db = new DatabaseManager(
$container,
new ConnectionFactory($container)
);
$this->db = $db;
$connection = $this->db->connection('sqlite');
$connection->setSchemaGrammar(new \Illuminate\Database\Schema\Grammars\SQLiteGrammar);
$connection->setQueryGrammar(new \Illuminate\Database\Query\Grammars\SQLiteGrammar);
$this->schema = new SchemaBuilder($connection);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment