登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-02-09 11:00:25 126浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《在 Golang 的单元测试中如何模拟 netconf 会话》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我正在使用 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 会话》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>