Changing the DB connection used by a WPDB object that already exists or passing it a mysqli
instance is not possible.
And if it was, it still wouldn’t work for other reasons.
if you want to access a new database connection you need to create a new WPDB instance:
$second_db = new WPDB( 'dbuser', 'dbpassword', 'dbname', 'dbhost' );
https://developer.wordpress.org/reference/classes/wpdb/__construct/
This leads you to a second fundamental problem though, for tests to work you need a clean slate, you can’t switch the DB halfway through a request to test something in a second DB.
$wpdb
still exists and any APIs you call would fetch data from the first database, and write to it.- If you replace
$wpdb
somehow you face a more insidious problem that WordPress pre-fetches and caches a lot of data in advance, leading to mismatched data from different databases
If you’re going to do this properly, there are much better ways to write tests that do support using a second database, aka the WP Unit test framework and PHPUnit, for details on that see the Testing chapter of the WordPress Core handbook on wordpress.org