执行唯一测试时,PUT 请求不会更新嵌套集合。
- 如果我运行所有测试套件
php bin/phpunit
,它就可以工作。 - 如果我通过 HTTP 客户端(Postman、cURL ...)发出请求,它就可以工作。
- 但是如果我只运行这个唯一的测试
php bin/phpunit --filter=testEditCategory
,它就会失败。其他所有字段(name
,description
此处)正在正确更新,但不是parameters
(集合Parameter
)。
我的应用程序的所有其他嵌套集合都观察到了与 PUT 请求相同的行为。
使用 :
- Symfony 5.2
- Api 平台 2.5.9
- 使用 hautelook/alice-bundle 2.8 的装置
运行测试:php bin/phpunit --filter=testEditCategory
以下测试不会通过:
class CategoryTest extends ApiTestCase {
use RefreshDatabaseTrait;
public function testEditCategory(): void
{
$data = [
'name' => 'Edited',
'description' => 'Edited',
"parameters" => []
];
$response = $this->request(
'PUT',
$this->getResourceIri(Category::class, ['name' => 'foobar']),
$data,
['Authorization' => 'Bearer '.self::VALID_JWT]
);
$json = json_decode((string)$response->getContent(), true, 512, JSON_THROW_ON_ERROR);
self::assertEmpty($json['parameters']);
}
// ...
返回:
1) App\Tests\Functional\Api\CategoryTest::testEditCategory
Failed asserting that an array is empty.
但是奇怪的行为出现了:当我之前执行任何其他 HTTP 请求时,进入测试方法......测试通过了:
// ...
$this->request('GET', 'https://www.google.com');
$response = $this->request(
'PUT',
$this->getResourceIri(Category::class, ['name' => 'category_1']),
$data,
['Authorization' => 'Bearer '.self::VALID_JWT]
);
// ...
ApiTestCase.php
:
class ApiTestCase extends WebTestCase
{
protected KernelBrowser $client;
/** @var string */
public const VALID_JWT = 'valid_token';
protected function setUp(): void
{
parent::setUp();
$this->client = static::createClient();
}
/**
* @param string $method
* @param string $uri
* @param mixed $content
* @param array $headers
* @return Response
* @throws JsonException
*/
protected function request(string $method, string $uri, $content = null, array $headers = []): Response
{
$server = ['CONTENT_TYPE' => 'application/ld+json', 'HTTP_ACCEPT' => 'application/ld+json'];
foreach ($headers as $key => $value) {
if ('content-type' === strtolower($key)) {
$server['CONTENT_TYPE'] = $value;
continue;
}
$server['HTTP_'.strtoupper(str_replace('-', '_', $key))] = $value;
}
if (is_array($content) && false !== preg_match('#^application/(?:.+\+)?json$#', $server['CONTENT_TYPE'])) {
$content = json_encode($content, JSON_THROW_ON_ERROR);
}
$this->client->request($method, $uri, [], [], $server, $content);
return $this->client->getResponse();
}
}
夹具:
App\Entity\Category:
category_1:
name: 'category_1'
description: 'category 1'
App\Entity\Parameter:
parameter_1:
name: 'parameter_1'
category: '@category_1'