Interfaces Make Testing Easier

I, along with others, have written on interfaces many times before but recently I had occasion to find a new thing about them that makes them really awesome. A few days ago I was tasked with implementing PHPUnit against a Zend Framework application. This application, like many others, makes use of Zend_Auth, and in doing so makes use of the Zend_Auth_Storage_Session class. The problem with unit testing is that sessions aren’t supported very well, and I ran into all kinds of challenges when I tried to use the existing functionality.

But it turns out that Zend Framework includes an interface, called Zend_Auth_Storage_Interface, which defines the methods that must exist in a storage object. The Zend_Auth_Storage_Session class implements this interface (as it’s required to do by the type hinting in the Zend_Auth::setStorage() method). This meant that I could mock a storage object, give my mocked object to the Zend_Auth::setStorage() method, and avoid all the issues surrounding sessions and unit testing. And what’s more, because the interface defined for me the methods that needed to be implemented, I could have confidence that my tests functioned properly.