下面的例子有助于我们在用PHPUnit测试Symfony控制器时处理动态响应内容。在这个例子中,id 和created_at 字段是动态的,所以每个响应会有不同的值。之所以数据总是动态的,是因为它们是由Doctrine DataFixtures加载的。
流程
-
setUp方法在运行每个测试案例之前重新加载数据固定装置。 -
replaceDynamicData方法将任何动态数据替换为指定规则的静态数据。 -
tearDownAfterClass方法在整个测试套件结束时重新加载数据夹具。
配置
这些配置是用来隔离test,dev 和prod 环境的,所以每个环境都有自己的数据库,如api_test,api_dev 和api 。
.env.dist
APP_ENV=dev
config/packages/doctrine.yaml
doctrine:
config/packages/test/doctrine.yaml
doctrine:
config/packages/dev/doctrine.yaml
doctrine:
phpunit.xml.dist
?xml version="1.0" encoding="UTF-8"?
安装
确保你已经安装了phpunit/phpunit 和symfony/browser-kit composer软件包。
测试文件
摘要测试
declare(strict_types=1);
CountryControllerTest
declare(strict_types=1);
测试
$ vendor/bin/phpunit --filter CountryControllerTest tests/Controller/CountryControllerTest.php