Mocking PDO(and other) Objects Inside Already Namespaced Classes

I’m back again addressing the issue of Mocking PDO and similar objects for unit-testing purposes. My previous post showed how to do so when testing a class that is not namespaced. It basically injected the class being tested into a namespace that contained a mock PDO class. This didn’t work with classes that are already in a namespace though.

The trick is to inject the mock PDO object into the namespace of the class being tested. To better explain, here is some code.

Class Being Tested:

This is mostly the same class that was being tested in the previous post. The only change is the addition of the namespace declaration on the first line.

The Technique

Like the last post, I am using eval() to do the injection. In most cases, you will know the namespace so you can simply hard-code it into the test. However, in my code I decided to dynamically get the namespace.


Notice that I had still had to hard-code the namespace in the “use … as …” line. I could have hard-coded it into the “new DBManager…” line instead but that wouldn’t really have changed anything. I wasn’t able to think of a way to accomplish that part dynamically.