Drupal - How to set the default theme programmatically
The current advice is to set this via config:
\Drupal::configFactory()
->getEditable('system.theme')
->set('default', $theme)
->save();
The previous method using ThemeHandlerInterface::setDefault()
is now deprecated.
You might need to install it first too, I'm not sure. In case you do:
\Drupal::service('theme_installer')->install(['test_theme']);