0

I already found few informations like Symfony2 access private services in tests or Replace Symfony service in tests for php 7.2

But I dont know why its not working.

I have an autowiring service.

class MailService {

    public function __construct(\Swift_Mailer $mailer, Environment $twig)
    {
        $this->mailer = $mailer;
        $this->twig = $twig;
    }

}

config/services_test.yaml

services:
    # default configuration for services in *this* file
    _defaults:
        #autowire: true      # Automatically injects dependencies in your services.
        #autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        public: true

    test.swiftmailer.transport: '@Swift_Mailer'

And when I try to replace.

        $mailer = $this->getMockBuilder(\Swift_Mailer::class)
            ->disableOriginalConstructor()
            ->getMock();
        $mailer->expects($this->once())->method('send')->willReturn(1);
        self::$container->set('swiftmailer.mailer.default', $mailer);
        self::$container->set('swiftmailer.default', $mailer);
        self::$container->set('swiftmailer.mailers', [$mailer]);

But I dont know why its not working.

Any ideas? :)

Patrick
  • 829
  • 2
  • 13
  • 34
  • 1
    Why would you need real services and DIC in unit tests? – svgrafov Apr 14 '20 at 20:32
  • Because I want to do ... – Patrick Apr 20 '20 at 17:14
  • But... why? You are already mocking the service, why don't you pass it directly to your class under test? – msg Oct 13 '20 at 22:25
  • 1
    A bit late to the party, but..... If you want to test the integration within your environment, you can definitely do this. i.e. using this kind of tests, you can test the integration of twig within your mailer service. Twig is heavily dependent on your configuration and of course the writen templates, and I think it's a good idea to have a test that covers this. Symfony also covers this type of tests in their documentation: https://symfony.com/doc/current/testing.html#integration-tests – nusje2000 Aug 26 '21 at 14:02
  • @nusje2000 while Symfony "covers" this in their documentation for some reason they don't actually cover how to override services... They seem to support the use case, but the actual DI container in tests doesn't support overriding (setting) already-initialized services, which is a problem (as per OP's question) and there doesn't seem to be a solution outside of just overriding the whole container and removing the check. – Amunak Aug 15 '22 at 10:12

0 Answers0