当无法封送数据中的值时,json.Marshal函数失败。诱发故障的唯一方法是引入测试字段,并在测试过程中滑入错误值: type DocData struct { … Test interface{} `json:"test,omitempty"`}…var induceFailure interface{}…docData.Test = induceFailuretxBytes, err := json.Marshal(docData)if err != nil { return false, fmt.Errorf("failed docData bytes marshalling: %s", err.Error())}…func TestMarshlFail(t *testing.T) { induceFailure = make(chan struct{}) defer func() { induceFailure= nil }() … 在这行代码上获得测试覆盖率可能不值得这么麻烦。 与手头的问题无关,下面是对代码的一些改进。 包装错误,而不是将错误转换为字符串:return nil, fmt.Errorf("failed docData unmarshalling: %w", err) 因为docData是一个指针,所以在解组时不需要取值的地址。err := json.U