Revert WordPress default options after a PHPUnit test has run

tl;dr: is there a way to make changes to WordPress options during a PHPUnit test suite execution, and have the changes reverted to the WordPress defaults before the next test suite is executed, without writing a custom teardown function?

Yes, and no.

No, you cannot use the code you currently have and expect this result. The test suite does use transactions and automatically roll back the database after each test. But you are making your changes in wpSetUpBeforeClass(), which runs before the transaction begins. Anything you do in wpSetUpBeforeClass() you have to clean up yourself in wpTearDownAfterClass(). This is by design.

However, you don’t have to use wpSetUpBeforeClass(). You could just place your code in setUp() instead. By calling parent::setUp() before making your changes, the database transaction will already have started and so your changes will be rolled back automatically after each test is complete.

Leave a Comment