使用 WP_UnitTestCase 时,如何临时切换主题并测试钩子?
解读
在国内一线 WordPress 外包或 SaaS 厂商的面试中,这道题考察的是**“单元测试环境下对主题生命周期与钩子系统的掌控能力”**。
面试官想确认你是否知道:
- 测试用例里不能简单调用
switch_theme(),因为WP_UnitTestCase在setUp()阶段已经加载了“虚拟主题”WP_UnitTestCase::_wp_theme。 - 必须在测试方法内部通过
tests_add_filter(‘stylesheet’)或tests_add_filter(‘template’)提前劫持选项,再手动触发do_action(‘after_switch_theme’)等关键钩子,才能保证临时主题切换与钩子注册同时生效。 - 测试结束后要显式回滚,否则后续测试会污染全局状态,CI 流水线会因此随机失败——这是国内很多团队判定候选人是否“靠谱”的硬指标。
知识点
- tests_add_filter() vs add_filter():前者在 PHPUnit 的
wp_tests_options阶段生效,比后者早一个生命周期。 - switch_theme() 在 CLI 环境下不会自动触发
after_switch_theme,必须手动do_action()。 - WP_UnitTestCase::go_to() 只能重置查询,不能重置主题;主题切换必须改
stylesheet选项。 - 全局回滚:利用
WP_UnitTestCase::$_backup_hooks或自己在tearDown()里remove_filter(),防止污染后续测试。 - CI 场景:GitHub Actions / Gitee Go 的容器里默认无
wp-content/themes,需提前git submodule拉取主题,否则switch_theme()返回WP_Error。
答案
class Theme_Hook_Test extends WP_UnitTestCase {
private $original_theme;
public function setUp(): void {
parent::setUp();
// 记录原始主题,用于回滚
$this->original_theme = get_option( 'stylesheet' );
}
public function test_custom_hook_in_target_theme() {
// 1. 临时切换主题:劫持 stylesheet 选项
tests_add_filter( 'stylesheet', function() {
return 'twentytwentythree'; // 目标主题目录
} );
tests_add_filter( 'template', function() {
return 'twentytwentythree';
} );
// 2. 手动触发主题切换钩子,让主题 functions.php 被加载
do_action( 'after_switch_theme', 'twentytwentythree', $this->original_theme );
// 3. 断言目标主题里的自定义钩子已注册
$this->assertTrue( has_action( 'wp_head', 'twentytwentythree_custom_meta' ) !== false );
// 4. 触发并验证
ob_start();
do_action( 'wp_head' );
$output = ob_get_clean();
$this->assertStringContainsString( '<meta name="generator" content="TT3"', $output );
}
public function tearDown(): void {
// 回滚主题
switch_theme( $this->original_theme );
parent::tearDown();
}
}
关键点:
- 用 tests_add_filter() 而不是
add_filter(),确保在wp_load_alloptions之前生效。 - 必须手动
do_action(‘after_switch_theme’),否则主题里的add_action()不会执行。 - 在
tearDown()中switch_theme()回滚,保证后续测试用例拿到干净环境。
拓展思考
- 多主题场景:如果插件需要兼容官方、第三方、自有主题,可在数据提供器里返回主题列表,循环切换并断言钩子差异,实现矩阵测试。
- 性能测试:在 CI 里用
wp timer统计after_switch_theme到wp_loaded的耗时,防止主题functions.php写死file_get_contents导致并发超时。 - 子主题支持:切换子主题时,需同时改
template(父)与stylesheet(子),并验证get_template_directory()与get_stylesheet_directory()返回值正确。 - 安全场景:国内等保测评要求“主题不可被恶意切换”,可在单元测试里 Mock
map_meta_cap,断言无switch_themes权限的用户调用switch_theme()返回WP_Error。