unit-testing - 结构字段还原

标签 unit-testing go struct

<分区>

我正在玩 Go,但在做一些测试时发现了这种奇怪的情况。

我正在使用结构中的方法将变量发送到另一个应该更改字段的方法,但是当我最后检查它时,该字段返回到第一个值,这让我感到困惑。

func (this TVManager) sendMessage(message string) {
    fmt.Println("5", this.connector)
    payload := map[string]string {
       "id": "0",
       "type": "request",
       "uri": "ssap://system.notifications/createToast",
       "payload": "{'message': 'This is a message'}"}
    this.connector.sendCommand(payload)
    fmt.Println("4", this.connector)
}

这是我正在测试的方法,它调用连接器的sendCommand。

func (this MockConnector) sendCommand(payload map[string]string) {
    fmt.Println("0", this)
    this.last_command = payload
    this.value = true
    fmt.Println("0", this)
}

我在模拟对象中使用的只是更改此结构字段的值。

    manager.sendMessage("This is a message")

fmt.Println("1", connector)
assert.Equal(t, expected, connector.last_command, "Command should be equal")

但是当我检查它时,它又回到了内部。我设置了一些打印品来尝试跟踪这些值,它们按预期更改了值,但随后又恢复了。

 1 {false map[]}
 5 {false map[]}
 0 {false map[]}
 0 {true map[uri:ssap://system.notifications/createToast payload:{'message': 'This is a message'} id:0 type:request]}
 4 {false map[]}
 1 {false map[]}
 --- FAIL: TestTVManagerSendsNotificationDownToConnector (0.00s)

这只是一个小程序,我将通过它来学习一些 Go,所以我很感激任何人能给我的帮助。

最佳答案

您正在按值传递结构。只要您不修改结构,这就可以正常工作,但如果您修改它,您实际上只是在修改一个副本。要使这项工作正常进行,您需要使用指向需要修改的结构的指针

代替:

func (this MockConnector) sendCommand(payload map[string]string)

使用:

func (this *MockConnector) sendCommand(payload map[string]string)

此外,在 Go 中使用 this(或 self)作为接收者名称被认为是一个坏主意,因为接收者与 this 其他语言的指针/引用。

另一个最佳实践是,如果给定类型的一个方法需要指针接收器,则该类型的所有方法都应该有指针接收器。这样无论值是否为指针,方法集都保持一致。

参见 method sets , 和 these FAQ answers获取更多信息。

关于unit-testing - 结构字段还原,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45874311/

相关文章:

go - 双向预加载“属于”关联

C++ 结构指针

unit-testing - 进行正式单元测试的最有说服力的方法是什么?

java - 在删除文件内容之前创建单元测试

go - 如何创建对象数组 - Go?

amazon-web-services - API 网关集成请求 HTTP header 未将查询字符串映射到 header

C++ 结构/vector 编译问题

c - 段错误和结构变量无法打印到文件

node.js - 使用 MongoDB 进行单元测试查询

c# - 使用 Moq 确定方法是否被调用