卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35462本站已运行396

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

如何在单元测试 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 。因此,您应该在测试成功之前修复该问题。

卓越飞翔博客
上一篇: 发送电子邮件时出现错误 wsarecv:现有连接被远程主机强行关闭
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏