Using PHPUnit on a Zend Framework application, how can I force the locale to be used for a given test?

627 views Asked by At

I am testing a multi-lingual site with phpunit. One of the tests I want to perform is that the application will detect the locale of the user and automatically redirect.

That is, user accesses the site on /. The application detects they're from France and redirects to /fr-FR/

The application does appear to do this, but trying to write a unit test for this seems impossible. I need to forge the locale for the purpose of the test. Can anyone advise?

2

There are 2 answers

2
JW. On

It's probably looking at the Accept-Language header that the browser sends. You can access this in PHP using $_SERVER['HTTP_ACCEPT_LANGUAGE']. It's a global, so in your test setup, you could change its value:

$_SERVER['HTTP_ACCEPT_LANGUAGE'] = "en";
1
Stephen Maher On

The solution has been to make the code itself more testable.

In my test I have:

    $locale = new Zend_Locale();

    $locale->setLocale('fr_FR');
    Zend_Registry::set('Zend_Locale', $locale); 

And now in my app I use:

    $locale = Zend_Locale::findLocale(); 
    $locale = new Zend_Locale($locale);

To set the locale. As findLocale checks the Zend_Registry for an entry first.