如何为googollee socket.io处理程序编写单元测试?

huangapple go评论62阅读模式
英文:

How to write unit test for googollee socket.io handlers

问题

我正在使用一个名为github.com/googollee/go-socket.io的Go库。
我想知道如何编写一个非常简单的连接事件测试,例如,如果我想检查是否返回了错误。

package main

import (
	"fmt"
	"log"
	"net/http"

	socketio "github.com/googollee/go-socket.io"
)

func main() {
	server := socketio.NewServer(nil)

	server.OnConnect("/", func(s socketio.Conn) error {
		s.SetContext("")
		fmt.Println("connected:", s.ID())
		return nil
	})
}
英文:

I am using a go lib: github.com/googollee/go-socket.io
I am wondering how to write a very simple test for connection event, ex, if i want to check no error is returned.

package main

import (
    "fmt"
    "log"
    "net/http"

    socketio "github.com/googollee/go-socket.io"
)

func main() {
    server := socketio.NewServer(nil)

	server.OnConnect("/", func(s socketio.Conn) error {
    	s.SetContext("")
	    fmt.Println("connected:", s.ID())
		return nil
    })
}

答案1

得分: 1

创建一个单独的函数,该函数以socketio.Conn接口作为参数,并将其传递给server.OnConnect,而不是使用匿名函数。

然后,您可以模拟socketio.Conn来对函数进行单元测试。

例如,将您的代码片段更改为:

package main

import (
    "fmt"
    "log"
    "net/http"

    socketio "github.com/googollee/go-socket.io"
)

func main() {
    server := socketio.NewServer(nil)

    server.OnConnect("/", handleOnConnect)
}

func handleOnConnect(s socketio.Conn) error {
    s.SetContext("")
    fmt.Println("connected:", s.ID())
    return nil
}

现在,您只需要测试handleOnConnect函数。因为socketio.Conn是一个接口,您可以创建一个模拟对象来测试该函数,而不必担心socketio的内部实现。

根据您的用例,您还可以创建一个新的接口,该接口是socketio.Conn的子集,以便更容易进行模拟。

英文:

Create a seperate function which takes the socketio.Conn interface as a parameter, and pass that to server.OnConnect instead of an anonymous function.

Then you can mock the socketio.Conn to unit test your function.

For example, change your code snippet to:

package main

import (
    "fmt"
    "log"
    "net/http"

    socketio "github.com/googollee/go-socket.io"
)

func main() {
    server := socketio.NewServer(nil)

    server.OnConnect("/", handleOnConnect)
}

func handleOnConnect(s socketio.Conn) error {
    s.SetContext("")
    fmt.Println("connected:", s.ID())
    return nil
}

Now, all you have to do is test handleOnConnect. Because socketio.Conn is an interface, you can create a mock to test this function without worrying about socketio internals.

You can also create a new interface which is a subset of socketio.Conn depending on your use case to make mocking easier.

huangapple
  • 本文由 发表于 2021年8月15日 15:27:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/68789527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定