symfony5创建单元测试: ①在测试环境中,这些环境文件被读取(如果其中有重复的变量,列表中较低的文件会覆盖之前的项目): .env:包含具有应用默认值的环境变量; .env.test:覆盖/设置特定的测试值或变量; .env.test.local: 覆盖本机的特定设置
例如:
# .env.test
# ...
DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name_test?serverVersion=5.7"
②生成测试类 应用程序测试是PHP文件,通常在应用程序的test/Controller/目录下。它们通常扩展WebTestCase。这个类在KernelTestCase的基础上增加了特殊的逻辑。 例如你想测试PostController类处理的页面,首先使用SymfonyMakerBundle的make:test命令创建一个新的PostControllerTest:
$php bin/console make:test
Which test type would you like?:
> WebTestCase
The name of the test class (e.g. BlogPostTest):
> Controller\PostControllerTest
会创建如下的测试类:
// tests/Controller/PostControllerTest.php
namespace App\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class PostControllerTest extends WebTestCase
{
public function testSomething(): void
{
// This calls KernelTestCase::bootKernel(), and creates a
// "client" that is acting as the browser
$client = static::createClient();
// Request a specific page
$crawler = $client->request('GET', '/');
// Validate a successful response and some content
$this->assertResponseIsSuccessful();
$this->assertSelectorTextContains('h1', 'Hello World');
}
}
