Home >Backend Development >Golang >How to mock netconf session in unit testing Golang
I am using juniper's netconf package ("github.com/juniper/go-netconf/netconf") to establish a netconf session in my code .
I want to know how to simulate a netconf session in a unit test.
My method is:
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 }
The problem occurs when myfunction() has a line that delays sess.close() and throws an error due to a nil pointer dereference
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 }
So, what changes can I make to the mockgetsshconnection() method so that sess.close() doesn't throw an error?
nil
The pointer error originates from the close
function when the underlying transport
is calledclose
when. Fortunately transport
is an interface
type that you can easily mock and use in a real instance of netconf.session
. For example, like this:
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 }
Note that the function you are testing currently returns 0
instead of the sessionid
of the session. Therefore, you should fix the issue before the test succeeds.
The above is the detailed content of How to mock netconf session in unit testing Golang. For more information, please follow other related articles on the PHP Chinese website!