首頁  >  文章  >  後端開發  >  如何在單元測試 Golang 中模擬 netconf 會話

如何在單元測試 Golang 中模擬 netconf 會話

WBOY
WBOY轉載
2024-02-12 15:42:16819瀏覽

如何在单元测试 Golang 中模拟 netconf 会话

問題內容

我正在使用juniper 的netconf 套件(「github.com/juniper/go-netconf/netconf」)在我的程式碼中建立netconf 會話。

我想知道如何在單元測試中模擬 netconf 會話。

我的方法是:

func testmyfunction(t *testing.t) {
    getsshconnection = mockgetsshconnection
    got := myfunction()
    want := 123
    if !reflect.deepequal(got, want) {
        t.errorf("error expectation not met, want %v, got %v", want, got)
    }
}
func mockgetsshconnection() (*netconf.session, error) {
    var sess netconf.session
    sess.sessionid = 123
    return &sess, nil
}

當 myfunction() 有一行延遲 sess.close() 並且由於 nil 指標取消引用而引發錯誤時,就會出現問題

func MyFunction() int {
    sess, err := getSSHConnection() // returns (*netconf.Session, error)
    if err == nil && sess != nil {
        defer sess.Close() -> Problem happens here
        // Calls RPC here and rest of the code here
        
    } 
    return 0
}

那麼,我可以對mockgetsshconnection()方法進行哪些更改,以便sess.close()不會拋出錯誤?

解決方法

nil 指標錯誤源自close 函數 當底層transport呼叫close時。幸運的是 transport 是一個 interface 類型,您可以輕鬆地在 netconf.session 的實際實例中模擬和使用它。例如像這樣:

type MockTransport struct{}

func (t *MockTransport) Send([]byte) error {
    return nil
}

func (t *MockTransport) Receive() ([]byte, error) {
    return []byte{}, nil
}

func (t *MockTransport) Close() error {
    return nil
}

func (t *MockTransport) ReceiveHello() (*netconf.HelloMessage, error) {
    return &netconf.HelloMessage{SessionID: 123}, nil
}

func (t *MockTransport) SendHello(*netconf.HelloMessage) error {
    return nil
}

func (t *MockTransport) SetVersion(version string) {
}

func mockGetSSHConnection() (*netconf.Session, error) {
    t := MockTransport{}
    sess := netconf.NewSession(&t)
    return sess, nil
}

請注意,您要測試的函數目前傳回 0 而不是會話的 sessionid 。因此,您應該在測試成功之前修復該問題。

以上是如何在單元測試 Golang 中模擬 netconf 會話的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除