Home > other >  Shopware 6 Production Unable to access plugin services from the container in a unit test
Shopware 6 Production Unable to access plugin services from the container in a unit test

Time:08-17

I setup a Unit Test in a Shopware custom (static) Plugin following this guide:

Shopware documentation

Everything runs fine and I'm able to run a unit test

class ProductReturnsTest extends TestCase
{
     use IntegrationTestBehaviour;
     use StorefrontPageTestBehaviour;

public function testConfirmPageSubscriber(): void
{
    $container = $this->getKernel()->getContainer();
    $dd = $container->get(CustomDataService::class); <== IT BREAKS HERE ServiceNotFoundException: You have requested a non-existent service 

    $dd = $container->get('event_dispatcher'); // WORKS WITH SHOPWARE ALIASES NOT WITH PLUGINS
}
}

I can make container->get on any shopware alias but as soon I try to recall and get from the container any service decleared in any xml of any 3th party plugin, i get

 ServiceNotFoundException: You have requested a non-existent service "blabla"

What is wrong ?

CodePudding user response:

Take a look at the answer given here: https://stackoverflow.com/a/70171394/10064036.

Probably your plugin is not marked as active in the DB your tests run against.

CodePudding user response:

The test environment has a mostly unpopulated database to allow tests to to run unaffected with their own fixtures only. Therefore after each test there should be a rollback to all transactions made within the test. This principle also includes plugin installations and database transactions they may execute in their lifecycle events.

You may want to install your plugin properly before your tests, so you get a representative state of the environment with the plugins lifecycle events getting dispatched and thereby caused possible changes.

public function setUp(): void
{
    $this->installPlugin();
}

private function installPlugin(): void
{
    $application = new Application($this->getKernel());
    $installCommand = $application->find('plugin:install');

    $args = [
        '--activate' => true,
        '--reinstall' => false,
        'plugins' => ['YourPluginName'],
    ];

    $installCommand->run(new ArrayInput($args, $installCommand->getDefinition()), new NullOutput());
}
  • Related