You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Go测试用例彼此完全独立执行?

Go测试函数独立执行的解决方案

我有两个Go测试函数,其中一个执行后会导致另一个失败。我清楚标准http库存在全局状态,会在多个测试之间保留。有人建议使用清理函数,但我认为测试本就不该互相影响,否则就失去了测试的意义。

复现代码

以下是可最小复现的示例代码main_test.go:

package main

import (
    "net/http"
    "testing"
    "time"
)

func start_server(t *testing.T) {
    err := http.ListenAndServe(":8090", nil)
    if err != nil {
        t.Errorf("server shut down: %s\n", err.Error())
    }
}

func TestA(t *testing.T) {
    go start_server(t)
    timer := time.NewTimer(time.Second)
    <-timer.C
}

func TestB(t *testing.T) {
    go start_server(t)
    timer := time.NewTimer(time.Second)
    <-timer.C
}

测试结果

同时运行两个测试

$ go test -v main_test.go
=== RUN   TestA
--- PASS: TestA (1.00s)
=== RUN   TestB
    main_test.go:12: server shut down: listen tcp :8090: bind: address already in use
--- FAIL: TestB (1.00s)
FAIL
FAIL    command-line-arguments  2.005s
FAIL

单独运行TestB

$ go test -v main_test.go -run TestB
=== RUN   TestB
--- PASS: TestB (1.00s)
PASS
ok      command-line-arguments  1.006s

问题

如何让这些测试完全独立执行?并行化不是必需的。

解决方案

问题出在测试之间的goroutine不会被自动终止,它们会在后台持续运行。目前只能接受这一设计现状,解决方案是实现服务的优雅关闭,这样即使某个测试发生panic,也不会悄无声息地影响其他测试。


内容的提问来源于stack exchange,提问作者GRASBOCK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 11:42:56