How to init Database connection in phpunit Functional test

Hi everyone!

I’m trying to write some functional tests for my application. I found this post Mezzio Example: Functional and Unit Testing - Marc Guyer which got me started somewhat, but the problem I’m having is that when I run the test, the application doesn’t have a connection to the database.

Cut down to the basics, the test has this setUp function, that initializes the app.

    protected function setUp(): void
    {   
        parent::setUp(); 
        $this->container = require __DIR__ . '/../config/container.php';
        $this->app = $this->container->get(Application::class);
        $factory = $this->container->get(MiddlewareFactory::class);
        (require __DIR__ . '/../config/pipeline.php')($this->app, $factory, $this->container);
        (require __DIR__ . '/../config/routes.php')($this->app, $factory, $this->container);
    }   

How can I ensure that the application, when I instantiate classes, has a database connection?

If I need to provide more information, please let me know!

Thanks in advance, Roel

For Mezzio you can use mezzio-test:

This will build your application container, bootstrap the mezzio Application (pipeline, routes) and registers a custom \Laminas\Stratigility\Middleware\ErrorHandler listener, which will just re-throw any exception. Thus, the native exception assertions can be used (eg. $this->expectException() in PHPUnit).

The container and router can also be retrieved with MezzioTestEnvironment->container() and ->router() , respectively.

However, initializing the app is not necessary, the container is sufficient:

/** @var Psr\Container\ContainerInterface $container */
$container = require __DIR__ . '/../config/container.php';

If you use laminas-db then:

$dbAdapter = $container->get(Laminas\Db\Adapter\AdapterInterface::class);