
Shopware 6 单元测试中,即使插件服务已正确注册,$container->get() 仍抛出 ServiceNotFoundException,根本原因通常是测试环境未激活插件——需确保插件在测试数据库中状态为 active = 1。
shopware 6 单元测试中,即使插件服务已正确注册,`$container->get()` 仍抛出 `servicenotfoundexception`,根本原因通常是测试环境未激活插件——需确保插件在测试数据库中状态为 `active = 1`。
在 Shopware 6 的集成测试(如使用 IntegrationTestBehaviour)中,容器仅加载已启用插件所声明的服务。与开发或生产环境不同,测试默认使用的 SQLite 内存数据库(或独立测试 DB)是空的——它不会自动同步 bin/console plugin:install 或管理后台中的插件激活状态。因此,即使你的插件已通过 services.xml 正确注册了 CustomDataService,若其记录未存在于 plugin 表中,或 active 字段为 0,Symfony 容器便完全忽略该插件的依赖注入配置,导致服务不可见。
✅ 正确做法:在测试类中显式激活插件
推荐在 setUp() 方法中调用 Shopware 提供的 installPlugin() 工具方法(来自 IntegrationTestBehaviour):
use PHPUnit\Framework\TestCase;
use Shopware\Core\Test\IntegrationTestBehaviour;
use Shopware\Core\Test\StorefrontPageTestBehaviour;
class ProductReturnsTest extends TestCase
{
use IntegrationTestBehaviour;
use StorefrontPageTestBehaviour;
protected function setUp(): void
{
parent::setUp();
// 激活当前插件(按插件技术名称,如 'MyProductReturns')
$this->installPlugin('MyProductReturns');
}
public function testConfirmPageSubscriber(): void
{
$container = $this->getKernel()->getContainer();
// ✅ 现在可安全获取自定义服务
$customData = $container->get(CustomDataService::class);
// 验证服务实例类型(可选)
$this->assertInstanceOf(CustomDataService::class, $customData);
}
}
⚠️ 注意事项:
-
installPlugin()会自动执行插件安装、激活、构建缓存,并触发plugin:refresh流程; - 插件技术名称(Technical Name)必须与
composer.json中的"name"字段或Resources/config/plugin.xml的<name></name>值严格一致(区分大小写); - 若测试使用 MySQL/PostgreSQL,请确保测试数据库连接配置正确,且
plugin表存在并可写; - 切勿在测试中手动执行 SQL 更新
plugin.active—— 应始终通过 Shopware 官方 API(如installPlugin())操作,以保证生命周期钩子(如InstallPluginEvent)正常触发。
? 总结:Shopware 的服务容器加载机制高度依赖插件激活状态。单元/集成测试不是“免配置环境”,而是需要显式模拟真实运行上下文。激活插件是让自定义服务进入容器的前提条件,缺失这一步将导致所有插件内声明的服务(无论是否在 services.xml 中正确配置)均不可解析。










