英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论