[TYPO3-dev] making t3lib_div mockable

Bastian Waidelich bastian at typo3.org
Wed Sep 16 12:25:15 CEST 2009


Hi all,

as you probably know, a unit test should only test _one_ class to avoid 
side-effects.
While writing unit tests for v4 extensions and core I'm often coming to 
a point where I can't test a single class because it instantiates new 
classes with t3lib_div::makeInstance().

And the problem with static classes/methods: you can't replace them by a 
mock object.
There have been discussions in the core list about turning t3lib_div 
into a singleton. So it would be called something like 
t3lib_div::getInstance()->makeInstance(...);

I think, that's a good idea - Though it would not directly solve the 
above issue. And it won't be there before v4.4 - if at all.

Even though it would be good to be able to mock all static classes & 
methods somehow in most of the cases I only want to be able to override 
t3lib_div::makeInstance.

So here my suggestion:
Add the functions
registerInstance($className, $instance)
and
unregisterInstance($className)

that would add the specified instance to the internal $instances 
collection.. so:

t3lib_div::registerInstance('MyClass', $myMock);
t3lib_div::makeInsance('MyClass'); // == $myMock;
t3lib_div::unregisterInstance('MyClass');

I know, this is a rather crude solution and in your own extensions you 
should try to avoid static classes and t3lib_div::makeInstance in "low 
level" methods. But for the existing classes it might be a way to go.. 
at least until there is a better way. What do you think?

I have just tested this and added a small patch.

Bastian
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: mockable_t3lib_div_makeinstance.patch
URL: <http://lists.typo3.org/pipermail/typo3-dev/attachments/20090916/ee06ba82/attachment.txt>


More information about the TYPO3-dev mailing list