How to properly test a service method that uses other servicesHow can I prevent SQL injection in PHP?Unit Testing C CodeWhat is Unit test, Integration Test, Smoke test, Regression Test?How do I check if a string contains a specific word?Testing a method which completely uses another objects methodsphpunit testing method that calls other class methods which need mockZF2 - Mocking service requested in Module.phpSwiftmailer not sending mail on Symfony2 service testMocking a service called by a controller from a WebTestCasephpunit testing method that calls other class methods which need mock returning null

What do teaching faculty do during semester breaks?

Automatic Habit of Meditation

What to do when you reach a conclusion and find out later on that someone else already did?

Why are so many countries still in the Commonwealth?

How to write a sincerely religious protagonist without preaching or affirming or judging their worldview?

How can I tell if there was a power cut while I was out?

How to copy a file transactionally?

Why is a dedicated QA team member necessary?

How do I address my Catering staff subordinate seen eating from a chafing dish before the customers?

How important is a good quality camera for good photography?

Are there any examples of technologies have been lost over time?

"I you already know": is this proper English?

Timing/Stack question about abilities triggered during combat

Is dd if=/dev/urandom of=/dev/mem safe?

3D Statue Park: U shapes

How can I prevent corporations from growing their own workforce?

How do professional electronic musicians/sound engineers combat listening fatigue?

Is there a reason why I should not use the HaveIBeenPwned API to warn users about exposed passwords?

Is it legal for private citizens to "impound" e-scooters?

Print sums of all subsets

Strange Cron Job takes up 100% of CPU Ubuntu 18 LTS Server

Why is my read in of data taking so long?

Memory capability and powers of 2

How do campaign rallies gain candidates votes?



How to properly test a service method that uses other services


How can I prevent SQL injection in PHP?Unit Testing C CodeWhat is Unit test, Integration Test, Smoke test, Regression Test?How do I check if a string contains a specific word?Testing a method which completely uses another objects methodsphpunit testing method that calls other class methods which need mockZF2 - Mocking service requested in Module.phpSwiftmailer not sending mail on Symfony2 service testMocking a service called by a controller from a WebTestCasephpunit testing method that calls other class methods which need mock returning null






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I'm stuck on how to properly test a method on a Symfony service which only purpose is to call other methods on other services.



Trying to unit test the method by mocking every dependency, and relative methods, it uses, just makes the test useless in my opinion, since what I'm testing, in a way, is just that the other services are called correctly.

Also, as I read on various sources, I shouldn't mock what I don't own, and basically all such methods use at least one (EntityManager, EncoderFactory, etc...)



Trying to function test it with booting the kernel, grabbing the service and calling the method was a nightmare, and I got stuck on asserting that emails was sent, since I need a client and a response to grab all the emails that've been sent from the profiler.



This is an example of such methods that I have to test:



public function postRequestCreatedActions(PrivacyRequest $request, $sendNotifications = true)

$this->customLogger->logRequest($request);
if ($sendNotifications)
$this->customMailer->sendRequestCreated($request);

$this->em->flush();



So, my question is: if there's a way to properly test methods like this (unit or functional), how should I test it?

If a method like this is untestable, and needs to be changed, or removed entirely, how do you advice to refactor it without clogging the controller that calls it (each one is called by a controller)? Or is moving all this logic to the controller the only way?










share|improve this question






























    2















    I'm stuck on how to properly test a method on a Symfony service which only purpose is to call other methods on other services.



    Trying to unit test the method by mocking every dependency, and relative methods, it uses, just makes the test useless in my opinion, since what I'm testing, in a way, is just that the other services are called correctly.

    Also, as I read on various sources, I shouldn't mock what I don't own, and basically all such methods use at least one (EntityManager, EncoderFactory, etc...)



    Trying to function test it with booting the kernel, grabbing the service and calling the method was a nightmare, and I got stuck on asserting that emails was sent, since I need a client and a response to grab all the emails that've been sent from the profiler.



    This is an example of such methods that I have to test:



    public function postRequestCreatedActions(PrivacyRequest $request, $sendNotifications = true)

    $this->customLogger->logRequest($request);
    if ($sendNotifications)
    $this->customMailer->sendRequestCreated($request);

    $this->em->flush();



    So, my question is: if there's a way to properly test methods like this (unit or functional), how should I test it?

    If a method like this is untestable, and needs to be changed, or removed entirely, how do you advice to refactor it without clogging the controller that calls it (each one is called by a controller)? Or is moving all this logic to the controller the only way?










    share|improve this question


























      2












      2








      2


      1






      I'm stuck on how to properly test a method on a Symfony service which only purpose is to call other methods on other services.



      Trying to unit test the method by mocking every dependency, and relative methods, it uses, just makes the test useless in my opinion, since what I'm testing, in a way, is just that the other services are called correctly.

      Also, as I read on various sources, I shouldn't mock what I don't own, and basically all such methods use at least one (EntityManager, EncoderFactory, etc...)



      Trying to function test it with booting the kernel, grabbing the service and calling the method was a nightmare, and I got stuck on asserting that emails was sent, since I need a client and a response to grab all the emails that've been sent from the profiler.



      This is an example of such methods that I have to test:



      public function postRequestCreatedActions(PrivacyRequest $request, $sendNotifications = true)

      $this->customLogger->logRequest($request);
      if ($sendNotifications)
      $this->customMailer->sendRequestCreated($request);

      $this->em->flush();



      So, my question is: if there's a way to properly test methods like this (unit or functional), how should I test it?

      If a method like this is untestable, and needs to be changed, or removed entirely, how do you advice to refactor it without clogging the controller that calls it (each one is called by a controller)? Or is moving all this logic to the controller the only way?










      share|improve this question
















      I'm stuck on how to properly test a method on a Symfony service which only purpose is to call other methods on other services.



      Trying to unit test the method by mocking every dependency, and relative methods, it uses, just makes the test useless in my opinion, since what I'm testing, in a way, is just that the other services are called correctly.

      Also, as I read on various sources, I shouldn't mock what I don't own, and basically all such methods use at least one (EntityManager, EncoderFactory, etc...)



      Trying to function test it with booting the kernel, grabbing the service and calling the method was a nightmare, and I got stuck on asserting that emails was sent, since I need a client and a response to grab all the emails that've been sent from the profiler.



      This is an example of such methods that I have to test:



      public function postRequestCreatedActions(PrivacyRequest $request, $sendNotifications = true)

      $this->customLogger->logRequest($request);
      if ($sendNotifications)
      $this->customMailer->sendRequestCreated($request);

      $this->em->flush();



      So, my question is: if there's a way to properly test methods like this (unit or functional), how should I test it?

      If a method like this is untestable, and needs to be changed, or removed entirely, how do you advice to refactor it without clogging the controller that calls it (each one is called by a controller)? Or is moving all this logic to the controller the only way?







      php symfony testing phpunit symfony-3.4






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 26 at 18:28









      b.enoit.be

      5,5744 gold badges28 silver badges42 bronze badges




      5,5744 gold badges28 silver badges42 bronze badges










      asked Mar 26 at 17:11









      ElsifoElsifo

      112 bronze badges




      112 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          0














          As I understand, you have to test method from your service. This method calls another services from injected dependencies. If so you have to instantiate service inside test using mocked dependencies or just arguments, for example (using prophecy with call method predictions):



          public function testPostRequestCreatedActions(): void

          $em = $this->prophesize(EntityManagerInterface::class);
          $em->flush()->willReturn(true)->shouldBeCalled();

          $request = $this->prophesize(PrivacyRequest::class);
          $logger = $this->prophesize(LoggerInterface::class);
          $logger->logRequest(Argument::any())->shouldBeCalled();

          $mailer = $this->prophesize(MailerInterface::class);
          $mailer->sendRequestCreated(Argument::any())->shouldNotBeCalled();

          $service = new Service($em->reveal(), $logger->reveal(), $mailer->reveal()); // assuming your service dependencies are in constructor

          $service->postRequestCreatedActions($request->reveal(), false);




          P.S This is not a copy paste example, just get the main idea






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55362727%2fhow-to-properly-test-a-service-method-that-uses-other-services%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            As I understand, you have to test method from your service. This method calls another services from injected dependencies. If so you have to instantiate service inside test using mocked dependencies or just arguments, for example (using prophecy with call method predictions):



            public function testPostRequestCreatedActions(): void

            $em = $this->prophesize(EntityManagerInterface::class);
            $em->flush()->willReturn(true)->shouldBeCalled();

            $request = $this->prophesize(PrivacyRequest::class);
            $logger = $this->prophesize(LoggerInterface::class);
            $logger->logRequest(Argument::any())->shouldBeCalled();

            $mailer = $this->prophesize(MailerInterface::class);
            $mailer->sendRequestCreated(Argument::any())->shouldNotBeCalled();

            $service = new Service($em->reveal(), $logger->reveal(), $mailer->reveal()); // assuming your service dependencies are in constructor

            $service->postRequestCreatedActions($request->reveal(), false);




            P.S This is not a copy paste example, just get the main idea






            share|improve this answer





























              0














              As I understand, you have to test method from your service. This method calls another services from injected dependencies. If so you have to instantiate service inside test using mocked dependencies or just arguments, for example (using prophecy with call method predictions):



              public function testPostRequestCreatedActions(): void

              $em = $this->prophesize(EntityManagerInterface::class);
              $em->flush()->willReturn(true)->shouldBeCalled();

              $request = $this->prophesize(PrivacyRequest::class);
              $logger = $this->prophesize(LoggerInterface::class);
              $logger->logRequest(Argument::any())->shouldBeCalled();

              $mailer = $this->prophesize(MailerInterface::class);
              $mailer->sendRequestCreated(Argument::any())->shouldNotBeCalled();

              $service = new Service($em->reveal(), $logger->reveal(), $mailer->reveal()); // assuming your service dependencies are in constructor

              $service->postRequestCreatedActions($request->reveal(), false);




              P.S This is not a copy paste example, just get the main idea






              share|improve this answer



























                0












                0








                0







                As I understand, you have to test method from your service. This method calls another services from injected dependencies. If so you have to instantiate service inside test using mocked dependencies or just arguments, for example (using prophecy with call method predictions):



                public function testPostRequestCreatedActions(): void

                $em = $this->prophesize(EntityManagerInterface::class);
                $em->flush()->willReturn(true)->shouldBeCalled();

                $request = $this->prophesize(PrivacyRequest::class);
                $logger = $this->prophesize(LoggerInterface::class);
                $logger->logRequest(Argument::any())->shouldBeCalled();

                $mailer = $this->prophesize(MailerInterface::class);
                $mailer->sendRequestCreated(Argument::any())->shouldNotBeCalled();

                $service = new Service($em->reveal(), $logger->reveal(), $mailer->reveal()); // assuming your service dependencies are in constructor

                $service->postRequestCreatedActions($request->reveal(), false);




                P.S This is not a copy paste example, just get the main idea






                share|improve this answer















                As I understand, you have to test method from your service. This method calls another services from injected dependencies. If so you have to instantiate service inside test using mocked dependencies or just arguments, for example (using prophecy with call method predictions):



                public function testPostRequestCreatedActions(): void

                $em = $this->prophesize(EntityManagerInterface::class);
                $em->flush()->willReturn(true)->shouldBeCalled();

                $request = $this->prophesize(PrivacyRequest::class);
                $logger = $this->prophesize(LoggerInterface::class);
                $logger->logRequest(Argument::any())->shouldBeCalled();

                $mailer = $this->prophesize(MailerInterface::class);
                $mailer->sendRequestCreated(Argument::any())->shouldNotBeCalled();

                $service = new Service($em->reveal(), $logger->reveal(), $mailer->reveal()); // assuming your service dependencies are in constructor

                $service->postRequestCreatedActions($request->reveal(), false);




                P.S This is not a copy paste example, just get the main idea







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 27 at 13:36

























                answered Mar 27 at 13:29









                alveryalvery

                6902 gold badges5 silver badges22 bronze badges




                6902 gold badges5 silver badges22 bronze badges


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55362727%2fhow-to-properly-test-a-service-method-that-uses-other-services%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript