Symfony4/Behat inject function not working "you have requested a non-existen service"

Viewed 195

For a testcase i need to be able to use an existing service, but this service cannot be used in my behat context:

Context:

/**
class CustomContext extends MinkContext implements KernelAwareContext {

    # ...

     * @param EntityManagerInterface $em
     * @param HttpCallResultPool $httpCallResultPool
     * @param SessionInterface $session
     * @param CustomService $customService
     * @param string $evaluationMode
     */
    public function __construct(
        EntityManagerInterface $em,
        HttpCallResultPool $httpCallResultPool,
        SessionInterface $session,
        CustomService $customService,
        string $evaluationMode = 'javascript'
    ) {
        $this->em = $em;
        $this->client = new Client();
        $this->inspector = new JsonInspector($evaluationMode);
        $this->httpCallResultPool = $httpCallResultPool;
        $this->session = $session;
        $this->customService= $customService;
    }

behat.yaml:

# ...
    Behat\Symfony2Extension:
      kernel:
        bootstrap: 'config/bootstrap.php' 
        path: 'src/Kernel.php'  
        class: 'App\Kernel' 
        env: dev 
        debug: false 

# ...
suites:
    default:
      contexts:
        - App\CustomContext:
            em: '@doctrine.orm.default_entity_manager'
            session: '@session'
            customService: '@App\Service\CustomService'

Fehlermeldung:

In Container.php line 289:
                                                                                                                             
  You have requested a non-existent service "App\Service\CustomService".

Can someone help or has an idea why this error message is shown? The Service does work in the used controller. So there should be no error with the service itself, only with injecting this service into behat.

2 Answers

Your service has to be public. You could either make it public "globally" in your regular services.yml or create an override for the test environment.

It's worth noting that there is another Symfony extension for Behat that uses your application's service container directly and supports autowiring. No need to handwire your services to your context classes anymore.

Related