Key Points
- In-memory database exists only in application memory and is a practical solution to test code that interacts with the database. They are easy to set up with Symfony applications using Doctrine and are ideal for testing due to their discardability.
- Symfony's test environment configuration allows the creation of discardable test databases. The configuration file that needs to be edited to set these databases is
app/config/config_test.php
. Support for in-memory databases using SQLite3 can facilitate testing by sending SQL queries to functional databases, eliminating the need to mock the repository classes. - When using an in-memory database in a test class, the schema must be built first, which means that the tables of the entity and any required fixtures must be loaded for the test suite. The database bootloader can be used to do most of the work, similar to forcing the Doctrine mode update console command to run.
Testing code that interacts with a database can be very painful. Some developers mock database abstractions, so there is no actual query to test. Other developers create test databases for development environments, but this can also be painful in terms of continuous integration and maintaining the state of this database. In-memory database is an alternative to these options. Since they are only present in the application's memory, they are truly one-time and very suitable for testing. Thankfully, these are very easy to set up with Symfony applications that use Doctrine. Try reading our guide on functional testing with Symfony to understand the end-to-end behavior of testing applications.
Symfony environment configuration
One of the most powerful features of the Symfony framework is the ability to create different environments with their own unique configurations. Symfony developers may ignore this feature, especially the lesser-known aspects of testing environments studied here. Symfony's guide on mastering and creating new environments explains how frameworks handle configurations of different environments and shows some useful examples. The configuration file that needs to be edited to set the discardable test database is app/config/config_test.php
. When accessing an application in a test suite, the kernel will load using the test environment and this configuration file will be processed.
In-memory database using Doctrine
SQLite3 supports in-memory databases and is very suitable for testing. With these databases, you can test your application by actually sending SQL queries to the functional database, thus eliminating the effortless simulation of repository classes with predefined behavior. The database will be new at the start of the test and will be cleanly destroyed at the end. To override the default Doctrine connection configuration, you need to add the following line to the test environment configuration file. If you have multiple Doctrine connections configured in your application, you may need to adjust it a little to match.
# app/config/config_test.yml doctrine: dbal: driver: pdo_sqlite memory: true charset: UTF8
Using database in test classes
When using this shiny new in-memory database in the test class, the schema must be built first. This means creating a table of entities and loading any fixtures required for the test suite. The following class can be used as a database bootstrap, which does most of the work. It has the same effect as forcing the Doctrine mode update console command to run.
<?php namespace Tests\AppBundle; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\SchemaTool; use Symfony\Component\HttpKernel\KernelInterface; class DatabasePrimer { public static function prime(KernelInterface $kernel) { // 确保我们处于测试环境中 if ('test' !== $kernel->getEnvironment()) { throw new \LogicException('Primer must be executed in the test environment'); } // 从服务容器获取实体管理器 $entityManager = $kernel->getContainer()->get('doctrine.orm.entity_manager'); // 使用我们的实体元数据运行模式更新工具 $metadatas = $entityManager->getMetadataFactory()->getAllMetadata(); $schemaTool = new SchemaTool($entityManager); $schemaTool->updateSchema($metadatas); // 如果您使用的是 Doctrine Fixtures Bundle,您可以在此处加载它们 } }
If you need an entity manager to test the class, you must apply the bootloader:
<?php namespace Tests\AppBundle; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Tests\AppBundle\DatabasePrimer; class FooTest extends KernelTestCase { public function setUp() { self::bootKernel(); DatabasePrimer::prime(self::$kernel); } public function testFoo() { $fooService = self::$kernel->getContainer()->get('app.foo_service'); // ... } }
In the example above, the container is used to get the service being tested. If this service depends on the entity manager, it will be built using the same entity manager booted in the setUp
method. If more control is needed, such as mocking another dependency, you can always retrieve the entity manager from the container and use it for manual instantiation of the class that needs to be tested. Using Doctrine Fixtures Bundle to populate a database with test data may also be a good idea, but it depends on your use case.
(The remaining FAQ part should be translated here to keep it consistent with the original text structure)
The above is the detailed content of Quick Tip: Testing Symfony Apps with a Disposable Database. For more information, please follow other related articles on the PHP Chinese website!

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Alipay PHP...

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.