英文:
How to test call expectation in Go
问题
我有一个名为MyClass的类需要测试。
MyClass有一个void方法,该方法调用内部服务器执行某些操作。
func (d *MyClass) SendToServer(args) {
// 做一些事情...
server.Send(myMessage)
}
我想模拟服务器调用Send方法,但由于该方法是一个void方法,我无法确定是否正确调用了它。
以下是我考虑的几种选项:
- 使用gomock,模拟服务器,并对服务的send方法设置期望。
- 创建自己的MockServer,并通过一系列验证来“覆盖”Send方法。类似于:
func (d *MockedServer) Send(message) {
// 验证消息...
}
- 创建自己的MockServer,但不是在方法内部验证期望,而是将消息添加到消息列表中,然后验证列表的内容。
在Go语言中,哪种方法更好?
英文:
I have a class MyClass that I want to test.
MyClass has a void method that calls an inner server to do something.
func (d *MyClass) SendToServer(args)
do stuff....
server.Send(myMessage)
I want to mock the server call Send, but since the method is a void method I can't be sure that I am actually calling it right.
These are the options I had in mind:
- Use gomock, mock the server, and set expectations on the send method of the service
- create my own MockServer, and "override" the method Send with a bunch of verifications. Something like:
func (d *MockedServer) Send(message)
// verify message...
- create my own MockServer, but instead of verifying the expectation within the method, add the message to a list of messages, and then verify the content of the list.
What is a better approach in Go?
答案1
得分: 2
你可以像这样将你的方法封装成一个函数:
var sendToServer = (*Server).Send
func (d *MyClass) SendToServer(args) {
// ...
sendToServer(server, msg)
// ...
}
在你的测试中可以这样使用:
func TestMyClass_SendToServer(t *testing.T) {
// ...
sent := false
sendToServer = func(*Server, args) {
sent = true
}
mc.SendToServer(args)
if !sent {
t.Error("fail")
}
}
这个技巧在Andrew Gerrand的Testing Techniques talk中有详细介绍。
英文:
You could make a function out of your method like this:
var sendToServer = (*Server).Send
func func (d *MyClass) SendToServer(args) {
// ...
sendToServer(server, msg)
// ...
}
And in your tests:
func TestMyClass_SendToServer(t *testing.T) {
// ...
sent := false
sendToServer = func(*Server, args) {
sent = true
}
mc.SendToServer(args)
if !sent {
t.Error("fail")
}
}
This is described in Andrew Gerrand's Testing Techniques talk.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论