VSCode Testing API下如何为测试启用播放按钮或CodeLens
问题原因及解决方法
你遇到的问题核心是仅将行号拼接在 URI 的hash段仅能支持跳转功能,VS Code 原生 Testing API 需要显式指定测试项的文本范围才会渲染编辑器内的运行按钮与 Code Lens。按以下步骤修改即可:
- 第一步:拆分 URI 与位置参数,显式设置
TestItem的range属性
注意 VS Code 的位置坐标为 0 起始,如果你获取到的测试源位置是 1 起始的行号,需要手动减 1 修正。修改代码示例如下:
const testUri = Uri.file(test.sourceLocation?.file); // 1-based行号转0-based const testLine = test.sourceLocation?.line ? test.sourceLocation.line - 1 : 0; const newTestItem = controller.createTestItem(test.id, test.labelName, testUri); // 配置测试项在文件中的行范围,VS Code 会基于这个范围渲染对应行的运行按钮 newTestItem.range = new Range( new Position(testLine, 0), new Position(testLine, Number.MAX_SAFE_INTEGER) ); testItem.children.add(newTestItem);
- 第二步:确保测试运行配置已正确注册
你需要调用createRunProfile注册默认运行/调试配置,且将第四个参数isDefault设为true,才会显示编辑器内的默认运行按钮,示例代码:
import * as vscode from 'vscode'; // 注册运行测试的配置项 controller.createRunProfile( '运行测试', vscode.TestRunProfileKind.Run, async (runRequest, cancellationToken) => { const testRunInstance = controller.createTestRun(runRequest); // 此处填写你的测试执行逻辑 }, true // 必须设为true,才会作为默认运行项显示在编辑器内 );
- 第三步:确认编辑器测试Code Lens配置正常
检查 VS Code 配置中testing.enableCodeLens项值为true,该配置默认开启,若被手动关闭会导致Code Lens不显示。
修改完成后重载扩展即可看到编辑器测试行旁的运行按钮。
内容的提问来源于stack exchange,提问作者The-DJ
相关产品推荐
相关产品推荐

