doufei3152 2018-02-21 05:07
浏览 115
已采纳

如何编写单元测试json.Marshal的失败案例?

I have following code:

func policyDocumentToStr(doc map[string]interface{}) (*string, error) {
   policy, err := json.Marshal(doc)
   if err != nil {
     log.Debugf("Error converting policy document to string. Error %s", err)
     return nil, err
   }

   policyAsString := string(policy)
   return &policyAsString, nil
}

I want to write a unit test which would cover the case of json.Marshal(doc) returning an error. Can anybody suggest how can I generate an error? What kind of input to function would result in error at line policy, err := json.Marshal(doc)?

  • 写回答

2条回答 默认 最新

  • douyan1903 2018-02-21 08:32
    关注

    Feed it a value that cannot be represented in JSON. There are many ways to do this, including creating a type with a custom marshaler that always returns an error. But one of the simplest ways is to try to marshal a channel:

    x := map[string]interface{}{
        "foo": make(chan int),
    }
    _, err := json.Marshal(x)
    fmt.Printf("Marshal error: %s
    ", err)
    

    Playground link

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记