首页  >  文章  >  后端开发  >  如何在单元测试 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删除