How to retain table data in wordpress phpunit tests

Usually, you don’t want to do this, as it might inadvertently affect tests that run after the test that creates the data.

If there is some data that you need to be available to several of your tests in a single testcase, you can create it with wpSetUpBeforeClass(), and then remove it again in wpTearDownAfterClass().

For example, the REST API category controller test from core:

class WP_Test_REST_Categories_Controller extends WP_Test_REST_Controller_Testcase {
    protected static $administrator;
    protected static $subscriber;

    public static function wpSetUpBeforeClass( $factory ) {
        self::$administrator = $factory->user->create( array(
            'role' => 'administrator',
        ) );
        self::$subscriber = $factory->user->create( array(
            'role' => 'subscriber',
        ) );
    }

    public static function wpTearDownAfterClass() {
        self::delete_user( self::$administrator );
        self::delete_user( self::$subscriber );
    }

    // [snip]
}

Otherwise, if you just want to keep some database changes from a test, perhaps for debugging purposes, you can use commit_transaction().

    public function test_something() {

        do_something();

        $this->commit_transaction();
    }