1 week ago

Mocked database class

Posted 1 week ago by hencca

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().

Please sign in or create an account to participate in this conversation.