vscode 無法除錯 golang testify suite 中的單個 test 的解決辦法


  • 問題描述
  • 網上的討論
  • 最終的解決辦法



package main

// Basic imports
import (


var assertObj *assert.Assertions

// Define the suite, and absorb the built-in basic suite
// functionality from testify - including a T() method which
// returns the current testing context
type ExampleTestSuite struct {
	VariableThatShouldStartAtFive int

// Make sure that VariableThatShouldStartAtFive is set to five
// before each test
func (suite *ExampleTestSuite) SetupTest() {
	suite.VariableThatShouldStartAtFive = 5
	assertObj = assert.New(suite.T())

// All methods that begin with "Test" are run as tests within a
// suite.
func (suite *ExampleTestSuite) TestExample() {
	assertObj.Equal(5, suite.VariableThatShouldStartAtFive)
	suite.Equal(5, suite.VariableThatShouldStartAtFive)

func (suite *ExampleTestSuite) TestExample2() {
	assertObj.NotEqual(51, suite.VariableThatShouldStartAtFive)

// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestExampleTestSuite(t *testing.T) {
	suite.Run(t, new(ExampleTestSuite))

點選 TestSuite 的某一個 Test* 方法上的 debug test,就會只除錯這單個 test,這是符合預期的。

但是在一個複雜專案中,如果 TestSuite 物件的 Test* 方法分佈於多個 *_test.go 檔案中,這時想要單獨執行某一個 Test*,就會出現 testing: warning: no tests to run 這樣的錯誤提示:


2022 年 4 月,github 上就有同樣問題的討論:
cannot debug single test in VS Code #1177
Failure to debug a suite test that is in a different file than the caller test #2414

一個回答是在 vscode 中使用 Go Nightly 外掛來代替 Go 外掛,收貨 4 個點贊,看樣子是可行的。

但是實際測試發現還是不行,替換外掛後,重啟了 vscode,依然不行。



.vscode/launch.json 中進行如下配置:

    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
            "name": "Debug TestMethodOne",
            "type": "go",
            "request": "launch",
            "mode": "test",
            "program": "${workspaceFolder}/pkg/service/service_test.go",
            "args": ["-test.run", "MyTestSuite/TestMethodOne"],
            "name": "Debug TestMethodTwo",
            "type": "go",
            "request": "launch",
            "mode": "test",
            "program": "${workspaceFolder}/pkg/service/service_test.go",
            "args": ["-test.run", "MyTestSuite/TestMethodTwo"],

然後就可以在 vscode 的 Debug 頁面中成功除錯單個 test 例項了