You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行PHPUnit测试时出现test.service_container错误求助

API Platform v3 测试容器错误排查问题

我基于API Platform(v3)开发了一个应用,编写了若干测试用例,但执行php bin/phpunit时触发test.service_container错误。改用API Platform官方Docker配置(composer + caddy)后测试可正常运行,因此推测问题出在自定义Docker配置中,但无法定位具体原因。以下是相关排查文件:

Login Test

<?php
declare(strict_types=1);
namespace App\Tests\Functional\Security;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use App\Security\Domain\Entity\User;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Uid\Uuid;

final class LoginTest extends ApiTestCase
{
    private static Connection|null $connection;

    public static function setUpBeforeClass(): void
    {
        parent::setUpBeforeClass();
        static::bootKernel();

        /** @var Connection $connection */
        $connection = static::getContainer()->get(Connection::class);
        static::$connection = $connection;

        (new Application(static::$kernel))
            ->find('doctrine:database:create')
            ->run(new ArrayInput(['--if-not-exists' => true]), new NullOutput())
        ;

        (new Application(static::$kernel))
            ->find('doctrine:schema:update')
            ->run(new ArrayInput(['--force' => true]), new NullOutput())
        ;
    }

    protected function setUp(): void
    {
        static::bootKernel();
        static::$connection?->executeStatement('TRUNCATE users');
    }

    public function testGetUser(): void
    {
        $client = static::createClient();

        /** @var EntityManagerInterface $em */
        $em = static::getContainer()->get(EntityManagerInterface::class);
        $repository = $em->getRepository(User::class);

        $user = new User(Uuid::v4(), 'user+2@email.com');
        $em->persist($user);
        $em->flush();

        $client->request('GET', sprintf('/api/users/%s', $user->id));

        $this->assertResponseIsSuccessful();
        $this->assertMatchesResourceItemJsonSchema(User::class);
        $this->assertJsonContains([
            'email' => 'user+2@email.com'
        ]);
    }

    public function testCreateUser(): void
    {
        $client = static::createClient();

        /** @var EntityManagerInterface $em */
        $em = static::getContainer()->get(EntityManagerInterface::class);
        $repository = $em->getRepository(User::class);

        $this->assertSame(0, $repository->count([]));

        $response = $client->request('POST', '/api/users', [
            'json' => [
                'email' => 'user+1@email.com'
            ]
        ]);

        $this->assertResponseIsSuccessful();
        $this->assertMatchesResourceItemJsonSchema(User::class);
        $this->assertJsonContains([
            'email' => 'user+1@email.com'
        ]);

        $id = Uuid::fromString($response->toArray()['id']);
        $user = $repository->find($id);

        $this->assertNotNull($user);
        $this->assertSame('user+1@email.com', $user?->email);
    }
}

Docker Compose 配置

version: '3.7'
services:
  php:
    container_name: burgu_api_php
    build: docker
    working_dir: /var/www/html
    user: '1000'
    ports:
      - "9000:8000"
    env_file:
      - .env
    depends_on:
      - database
      - mailer
    volumes:
      - .:/var/www/html
    networks:
      - default
  mailer:
    image: schickling/mailcatcher
    container_name: burgu_api_mailer
    ports: [ "1025", "1080" ]
    networks:
      - default
  database:
    image: postgres:13-alpine
    container_name: burgu_api_db
    environment:
      POSTGRES_DB: burgu_api_db
      POSTGRES_PASSWORD: password
      POSTGRES_USER: root
    env_file:
      - .env
    volumes:
      - database:/var/lib/postgresql/data:rw
    ports:
      - "5432"
    networks:
      - default
  database-test:
    image: postgres:13-alpine
    container_name: burgu_api_db_test
    environment:
      POSTGRES_DB: burgu_api_db_test
      POSTGRES_PASSWORD: burgu
      POSTGRES_USER: burgu
    volumes:
      - database-test:/var/lib/postgresql/data:rw
    ports:
      - "5433:5432"
volumes:
  database:
  database-test:

PHP Dockerfile

FROM php:8.1-cli
RUN apt-get update \
    &&  apt-get install -y --no-install-recommends \
        locales apt-utils git libicu-dev g++ libpng-dev libxml2-dev libzip-dev libonig-dev libxslt-dev unzip libpq-dev nodejs npm wget \
        apt-transport-https lsb-release ca-certificates sudo
RUN echo "en_US.UTF-8 UTF-8" > /etc/locale.gen  \
    &&  echo "fr_FR.UTF-8 UTF-8" >> /etc/locale.gen \
    &&  locale-gen
RUN curl -sS https://getcomposer.org/installer | php -- \
    &&  mv composer.phar /usr/local/bin/composer
RUN curl -sS https://get.symfony.com/cli/installer | bash \
    &&  mv /root/.symfony5/bin/symfony /usr/local/bin/symfony
RUN docker-php-ext-configure \
            intl \
    &&  docker-php-ext-install \
            pdo pdo_mysql pdo_pgsql opcache intl zip calendar dom mbstring gd xsl
RUN pecl install apcu && docker-php-ext-enable apcu
RUN npm install --global yarn
RUN adduser www-data sudo
RUN usermod -u 1000 www-data
RUN passwd --delete www-data
RUN mkdir -p /var/cache/symfony \
    && chown -R www-data:www-data /var/cache/symfony \
    && chown -R www-data:www-data /var/www \
    && chown -R www-data:www-data /usr/local/bin/composer \
    && chown -R www-data:www-data /usr/local/bin/symfony
CMD tail -f /dev/null

Kernel 代码

<?php
declare(strict_types=1);
namespace App\Shared\Infrastructure\Symfony;

use App\Shared\Application\Command\CommandHandlerInterface;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

final class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    protected function configureContainer(ContainerConfigurator $container): void
    {
        $container->import(sprintf('%s/config/{packages}/*.{php,yaml}', $this->getProjectDir()));
        $container->import(sprintf('%s/config/{packages}/%s/*.{php,yaml}', $this->getProjectDir(), (string) $this->environment));
        $container->import(sprintf('%s/config/{services}/*.php', $this->getProjectDir()));
        $container->import(sprintf('%s/config/{services}/%s/*.php', $this->getProjectDir(), (string) $this->environment));
    }

    protected function configureRoutes(RoutingConfigurator $routes): void
    {
        $routes->import(sprintf('%s/config/{routes}/%s/*.{php,yaml}', $this->getProjectDir(), (string) $this->environment));
        $routes->import(sprintf('%s/config/{routes}/*.{php,yaml}', $this->getProjectDir()));
    }

    protected function build(ContainerBuilder $container): void
    {
        $container->registerForAutoconfiguration(CommandHandlerInterface::class)
            ->addTag('messenger.message_handler', ['bus' => 'command.bus'])
        ;
    }
}

内容的提问来源于stack exchange,提问作者thibautthouement

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:05:33