1 回答

TA貢獻1784條經驗 獲得超8個贊
作為初始化過程的一部分,您可以在啟動測試套件之前嘗試連接到服務器。
例如,我在測試中通常有這樣的函數:
// waitForServer attempts to establish a TCP connection to localhost:<port>
// in a given amount of time. It returns upon a successful connection;?
// ptherwise exits with an error.
func waitForServer(port string) {
? ? backoff := 50 * time.Millisecond
? ? for i := 0; i < 10; i++ {
? ? ? ? conn, err := net.DialTimeout("tcp", ":"+port, 1*time.Second)
? ? ? ? if err != nil {
? ? ? ? ? ? time.Sleep(backoff)
? ? ? ? ? ? continue
? ? ? ? }
? ? ? ? err = conn.Close()
? ? ? ? if err != nil {
? ? ? ? ? ? log.Fatal(err)
? ? ? ? }
? ? ? ? return
? ? }
? ? log.Fatalf("Server on port %s not up after 10 attempts", port)
}
然后在我的TestMain()
我做:
func TestMain(m *testing.M) {
? ? go startServer()
? ? waitForServer(serverPort)
? ? // run the suite
? ? os.Exit(m.Run())
}
- 1 回答
- 0 關注
- 148 瀏覽
添加回答
舉報