3

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.

CasualBen
  • 829
  • 8
  • 22
  • there was a similar [question](https://stackoverflow.com/questions/6213628/keep-getting-you-have-requested-a-non-existent-service-test-client-in-symfon) on SO which recommended to look at https://symfony.com/doc/current/reference/configuration/framework.html#test – meewog Aug 03 '20 at 10:01
  • Thanks, but tried that already, but it did not help. I think it must be caused not by symfony but bei behats try to inject the service – CasualBen Aug 03 '20 at 12:25

2 Answers2

1

You could inject the container and access private services as explained here: https://symfony.com/blog/new-in-symfony-4-1-simpler-service-testing

dRamentol
  • 1,010
  • 10
  • 13
0

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.

Philip Weinke
  • 1,804
  • 1
  • 8
  • 13