Symfony 控制器测试由于 DTO 映射而失败

问题描述 投票:0回答:1

如何测试采用 DTO 的 Symfony 控制器?我正在遵循有关测试和 DTO 的官方文档,但在运行测试时出现此错误。

代码本身可以工作,我已经用邮递员尝试过 API。但由于某种原因,测试似乎无法将请求映射到 DTO。我该如何解决这个问题?

1) App\Tests\Feature\SignUp\Application\Http\Controller\Api\SignUpControllerTest::testSuccessfulSignUp
Symfony\Component\DependencyInjection\Exception\RuntimeException: Cannot autowire service "App\Feature\SignUp\Application\Transfer\ProfileTransfer": argument "$firstName" of method "__construct()" is type-hinted "string", you should configure its value explicitly.

DTO 看起来像文档中描述的那样,并且控制器可以工作,但测试有问题。它们是嵌套的 DTO,我有一个 SignUpTransfer,然后使用 UserTransfer 和 ProfileTransfer。

readonly class ProfileTransfer
{
    public function __construct(
        #[Assert\NotBlank()]
        #[Assert\Length(min: 2, max: 64)]
        public string $firstName,
        #[Assert\NotBlank()]
        #[Assert\Length(min: 2, max: 64)]
        public string $lastName
    ) {
    }

测试代码

    protected function apiRequest(string $url, string $method, $data)
    {
        $client = static::createClient();

        return $client->request($method, $url, [], [], ['CONTENT_TYPE' => 'application/json'], json_encode($data, JSON_THROW_ON_ERROR));
    }

    public function testSuccessfulSignUp(): void
    {
        $this->apiRequest('/sign-up', 'POST', [
            'user' => [
                'email' => '[email protected]',
                'password' => 'testtest'
            ],
            'profile' => [
                'firstName' => 'John',
                'lastName' => 'Doe'
            ]
        ]);

        self::assertResponseStatusCodeSame(201);
        self::assertResponseHeaderSame('Content-Type', 'application/json');
    }
api symfony testing dto
1个回答
0
投票

如果您通过 DI 作为服务注入

ProfileTransfer
,则需要将这些值添加到服务配置中。但我不认为你是这样使用的。

如果您始终手动创建它,请将其排除在服务之外:

# services.yaml
services:
    App\:
        resource: 'src/*'
        exclude:
            - 'src/DTO'
            - 'src/Feature/SignUp/Application/ProfileTransfer.php'
© www.soinside.com 2019 - 2024. All rights reserved.