package mainimport ( "net/http" "sync" "time")type SessionInterface1 interface { doLoginAndReadDestinations1() bool}type Session1 struct { sessionCookie string mux sync.Mutex sessionTime time.Time targetAddress string currentJwt string transport *http.Transport}var currentSession1 Session1func main() { currentSession1.verifyLogin1()}func (s *Session1) doLoginAndReadDestinations1() bool { ..logic... ... for example return true}func callDest1(si SessionInterface1) bool { return si.doLoginAndReadDestinations1()}func (s *Session1) verifyLogin1() bool { return callDest1(s)}我想創建單元測試并模擬 doLoginAndReadDestinations1 我嘗試為此方法創建接口并創建測試func test1(t *testing.T) { type args struct { } tests := []struct { name string args args want bool }{{ name: "test", args: args{}, want: false, }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var s1 *Session1 count := 10 s1 = &Session1{"", sync.Mutex{}, time.Now(), "", "", nil} var got1 = s1.verifyLogin() if got1 != tt.want { t.Errorf("getJwt() = %v, want %v", got, tt.want) } }) }}我不知道如何在測試中更改函數 doLoginAndReadDestinations1 的邏輯并更改第一個 main 中的邏輯
1 回答

躍然一笑
TA貢獻1826條經驗 獲得超6個贊
您將需要抽象出您想要模擬的所有內容。與其將依賴項解析為具體實現,不如使用接口。然后您將能夠創建一個將實現此接口的模擬。
一般來說,我會建議你stretr/testify進行測試。它有以下方法:
斷言
要求
嘲笑
套房
該庫將幫助您構建測試、編寫測試并刪除樣板代碼。它內部有模擬機制。
- 1 回答
- 0 關注
- 135 瀏覽
添加回答
舉報
0/150
提交
取消