Summer Sale! All accounts are 50% off this week.

hencca's avatar

Mocked database class

Hi, I'm running Unit tests against a old codebase by other people. I would like to do as little changes to the codebase a s possible, preferably none. The codebase has a db.php class that basically is used quite frequently around the codebase like this $db = new DB(); $db->connect();

the connect method creates a new PDO and tries to connect to a server. This server doesn't exist in my testing environment, nor does my app even need to hit the database for the tests to run. I am able to mock DB class in my tests, but is there a way to have new DB() return a mocked object while running the test? Because some tests run code in the app that do (new DB())->connect(); I had an idea that the constructor of DB would return a global mocked object if one existed, but it failed, and it is my understanding that it's not possible to return another object in __construct().

0 likes
3 replies
bobbybouwmann's avatar

Nope, you can't mock that behavior.

A solution is injecting the DB class in the class that uses it, but that requires changes for the old code. Another solution is using an interface to inject the class as well, but this all requires code changes.

To make this work in the best way you probably need a service container so you can swap the instance on run time.

Maybe writing a test with the DB isn't that bad?

hencca's avatar

Alright, thanks! I believe I will check in the connect() method for an APP_ENV=testing before trying to connect to the database. It's the least amount of changes

Please or to participate in this conversation.