gpt4 book ai didi

go - 函数 TestMain 没有运行

转载 作者:IT王子 更新时间:2023-10-29 02:00:42 28 4
gpt4 key购买 nike

似乎我的 func TestMain 没有运行

我的测试文件夹 /_test 中有 2 个文件。一个是/main_test.go,另一个是/api_city_find_all_test.go

我运行第二个,出现 panic 错误,说我得到了 nil 指针运行

谁能帮我解决这个问题?

ma​​in_test.go

func TestMain(m *testing.M) {

fmt.Print("TEST@@")

os.Chdir("../../../")

boot.Bootstrap()

rajaongkir.Register()

os.Exit(m.Run())
}

我跑
api_city_find_all_test.go

func TestApiCityFindAllTest(t *testing.T) {
goreq := libraries.Request("http://localhost:8181").Post([]string{"rajaongkir/city/findAll"}, nil, `{}`)

req, _ := goreq.MakeRequest()
resp := httptest.NewRecorder()

fmt.Print("TEST!!")

utilities.Globals.Router.ServeHTTP(resp, req)

respBody, _ := ioutil.ReadAll(resp.Body)

t.Log(string(respBody))

assert.NotEqual(t, "null", string(respBody))
}

我期待“测试!!”在 api_rajaongkir_city_find_all_test.go 和 main_test.go 中的“TEST@@”被打印但只是“TEST!!”显示出来,说明main_Test.go没有运行

最佳答案

TestMain函数是测试包的本地函数。

If a test file contains a function:

func TestMain(m *testing.M)

then the generated test will call TestMain(m) instead of running the tests directly.

您必须确保两个文件定义相同的包或在两个文件中定义 TestMain(m)

关于go - 函数 TestMain 没有运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56054284/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com