unit-testingmockingphpunitsymfony4prophecy

Symfony PhpUnit to mock PHP built-in method


I am using prophesize method to mock Class

Example:

$user = $this->prophesize(User::class);

How to mock PHP built-in method?

exactly I need to mock locale_accept_from_http($language);

Do you have idea how to handle this?


Solution

  • You don't mock PHPs native method, but instead write a wrapper for everything you need.

    class LocaleListener
    {
        protected $language;
    
        public function __construct($language) {
            $this->language = $language;
        }
    
        public function getPreferredLocale() {
            return locale_accept_from_http($this->language);
        }
    }
    

    And now you can mock that with:

    $listener = $this->prophesize(LocaleListener::class);
    $listener->getPreferredLocale()->willReturn('en_GB');
    

    Any if your are interested in the way Symfony proposes to handle the users locale from the header, check out this EventListener in their demo app: https://github.com/symfony/demo/blob/master/src/EventSubscriber/RedirectToPreferredLocaleSubscriber.php