Skip to content

HowTo - PHPUnit MockObject and the problem with "get_class()"

I know it's not the right way but if you are dealing with legacy code or find good reasons (like not storing the class name a database), if is needed that you have to use the php core function "get_class()". While you are implementing a unittest, you want to mock unneeded objects to focus on the area you need to test. Thats why you create a mockobject like:

$myMock->getMockBuilder('\My\Class')->getMock();
Problem with that, the return value of "get_class()" is something like "Mock_Class_b9e94bdd". Pretty frustrating if you ask me. After a long time of thinking and talking with other developers, we established the following solution.
abstract class AbstractClass { public function getClassName() { return get_class($this); } }
Now you only have to rewrite the code that is using "get_class()" by "$myClass->getClassName()". Du to the fact that $this represents the object, you don't have to trouble with late static bindings. Everything is working out of the box and you have touched a well known area of your code. I have added a example on one of my github repositories. By the way, don't get miss leaded by the method "setMockClassName()" provided by the "MockBuilder". If you use this method, your mock object has no mockmethods (like "expects()") anymore.

Trackbacks

Keine Trackbacks

Kommentare

Ansicht der Kommentare: Linear | Verschachtelt

Noch keine Kommentare

Kommentar schreiben

Die angegebene E-Mail-Adresse wird nicht dargestellt, sondern nur für eventuelle Benachrichtigungen verwendet.
Um einen Kommentar hinterlassen zu können, erhalten Sie nach dem Kommentieren eine E-Mail mit Aktivierungslink an ihre angegebene Adresse.

Um maschinelle und automatische Übertragung von Spamkommentaren zu verhindern, bitte die Zeichenfolge im dargestellten Bild in der Eingabemaske eintragen. Nur wenn die Zeichenfolge richtig eingegeben wurde, kann der Kommentar angenommen werden. Bitte beachten Sie, dass Ihr Browser Cookies unterstützen muss, um dieses Verfahren anzuwenden.
CAPTCHA

Markdown-Formatierung erlaubt
Formular-Optionen