I have the a service definition in a custom Drupal 8 module which I would like to test. I've managed to test everything else in my module with unit tests, so my whole suite runs in a fraction of a second, and I'd like to avoid introducing anything Simpletest-based. (My CI infrastructure wouldn't support it anyway.) Is there any way to test my service definition in an isolated unit test? Here's my service definition:


services: my_module.client: class: Drupal\my_module\Client factory: Drupal\my_module\Client::create arguments: ['@state', '@config.factory']

The manual test I've been performing is to run this Drush command:

drush ev 'var_dump(\Drupal::service("my_module.client")->_serviceId == "my_module.client" ? "PASS" : "FAIL");'

That's a sufficient smoke test while I'm developing. For a regression test, I'd also like to assert that the class returned is an instance of the correct type.

  • Are you trying to test the service definition in the YAML file? Or are you trying to test the container code? I think these are covered by core's unit tests because it's not your module's code that is doing the instantiating. For instance ContainerTest tests setting a service in the container and YamlFileLoader comes from Syfmony and tested there. I would test the class methods itself, but it's possible to set the object into the container for a given service id and assert that it's returned via \Drupal::service(). – mradcliffe Dec 4 '15 at 12:55
  • I think what I'm really after is proving that my service definition YAML causes the correct dependencies to be injected into my service class. Maybe that's an integration test by definition. – TravisCarden Dec 5 '15 at 3:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.