In the unit tests, the database is initialized in MediaWikiTestCase::run(). Since e638075, it is initialized "once" per class type (whatever is the result of needsDB() because it’s a OR) or when needsDB() is true.
On classes where no database is needed, the database is initialised anyway, it shouldn’t. This makes the tests unnecessarily take a bit longer. The change https://gerrit.wikimedia.org/r/#/c/328718 was meant to fix this thing, but an additional issue appeared: the test database is the object property $db, but its state is controlled by a static variable ($dbSetup) which is not kept in sync with $db, because when the object is destroyed the $db is unset but $dbSetup remains. In the next test, the $db is not initialized (since $dbSetup is true) but the test expects it is and $this->db->whatever() fails.
In MediaWikiTestCase::run() there is a TODO comment indicating the DB setup should be done in setUpBeforeClass. If this is chosen, all DB-related variables will be static and should be consistently initialized and destroyed.
This bug is created to track the small refactoring/rewrite of the part of code used to initialise and destruct the database in the tests, in order to finally submit the proposed patch https://gerrit.wikimedia.org/r/#/c/328718 without any error. It will also improve T93556. Possibly, if the code is moved in setUpBeforeClass, it should be checked that this new setup is supported by major extensions.