Write UnitTest for Symfony EventListener

后端 未结 1 863
时光说笑
时光说笑 2020-12-29 05:25

I have a SymfonyBundle here, which is really not more then a custom EventDispatcher, and an EventListener.

How would I go about unit testing this code ?

I kn

1条回答
  •  囚心锁ツ
    2020-12-29 06:07

    You can unit test your listener by mocking up all the necessary stuff it needs to work, for example, from a project of mine:

    class UploadListenerTest extends \PHPUnit_Framework_TestCase
    {
        public function testOnUpload()
        {
            $session = new Session(new MockArraySessionStorage());
            $file = new File(__FILE__);
    
            $event = new PostPersistEvent($file, new EmptyResponse, new Request(), "", []);
    
            $listener = new UploadListener($session);
            $listener->onUpload($event);
    
            $tempFiles = $session->get('_temp_files');
    
            $this->assertCount(1, $tempFiles);
            $this->assertEquals($tempFiles[0], $file->getFilename());
    
            $otherFile = new File(__FILE__);
    
            $event = new PostPersistEvent($otherFile, new EmptyResponse, new Request(), "", []);
    
            $listener->onUpload($event);
    
            $tempFiles = $session->get('_temp_files');
    
            $this->assertCount(2, $tempFiles);
            $this->assertEquals($tempFiles[0], $file->getFilename());
            $this->assertEquals($tempFiles[0], $otherFile->getFilename());
        }
    } 
    

    As you can see, I am creating every object my Event Listener needs in order to unit test it's behaviour.

    You can also go the functional way. Boot the Symfony kernel and create the conditions for your event to trigger, and then test the expected conditions you need to have after the event is triggered:

    public function testUploadNoFilesNoAjaxLoggedUser()
    {
        $this->loginUser($this->getDummyUser());
    
        $response = $this->requestRoute(self::UPLOAD_ROUTE, "POST");
    
        $this->assertResponseRedirect("panel_index", $response);
    }
    

    As you can see, I'm first logging the user and then doing an actual request to the upload form. After that I assert that my response should be a redirection to the main panel. Symfony is triggering the event under the hood, and this event is returning the RedirectResponse I need to assert.

    My recommendation is that you try to write both unit and functional tests, it will leave your application in a more stable state.

    EDIT

    Added answer to specific question on how to test an event dispatcher itself in this PR:

    https://github.com/whitewhidow/AsyncDispatcherBundle/pull/1/files

    0 讨论(0)
提交回复
热议问题