【问题标题】:How to write unit test failure for json.NewDecoder.Decode?如何为 json.NewDecoder.Decode 编写单元测试失败?
【发布时间】:2022-11-04 00:15:06
【问题描述】:

我必须为一个函数编写单元测试,这个函数使用json.NewDecoder.Decode

var infos models.RegisterInfos // struct with json fields
err := json.NewDecoder(r.Body).Decode(&infos)
if err != nil {
    // do something
}

如何在 json.NewDecoder(r.Body).Decode(&infos) 的单元测试中模拟错误(使用 testing 包)?我尝试查看NewDecoderDecode 源代码,但我找不到任何可以在几行内产生错误的内容。

【问题讨论】:

  • 在正文中添加语法错误。将 body 中的值更改为不适合目标类型的类型(例如,将 bool 解组为 struct)。

标签: json unit-testing go


【解决方案1】:

您可以发送像 <invalid json> 这样的正文:

func main() {
    body := "<invalid json>"
    var infos RegisterInfos // struct with json fields
    err := json.NewDecoder(strings.NewReader(body)).Decode(&infos)
    if err != nil {
        fmt.Println(err)
    }
}

https://go.dev/play/p/44E99D0eQou

【讨论】:

    【解决方案2】:

    给它一个无效的输入,或者解码成一个无效的输出:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "strings"
        "testing"
    )
    
    type Message struct {
        Name string
    }
    
    func TestDecodeFail(t *testing.T) {
        for _, tc := range []struct {
            in   string
            desc string
            out  any
        }{
            {`{Name: "Bobby"}`, "key without quotes", &Message{}},
            {`{"Name": "Foo"a}`, "extra character", &Message{}},
            {`{"Name": "Foo"}`, "bad destination", &struct{ Name int64 }{}},
            {`{"Name": "Foo` + "u001a" + `"}`, "invalid character", &Message{}},
        } {
            err := decode(tc.in, tc.out)
            if err != nil {
                fmt.Printf("%s -> %s, %T
    ", tc.desc, err.Error(), err)
            }
        }
    }
    
    func decode(in string, out any) error {
        return json.NewDecoder(strings.NewReader(in)).Decode(out)
    }
    

    输出:

    key without quotes -> invalid character 'N' looking for beginning of object key string, *json.SyntaxError
    extra character -> invalid character 'a' after object key:value pair, *json.SyntaxError
    bad destination -> json: cannot unmarshal string into Go struct field .Name of type int64, *json.UnmarshalTypeError
    invalid character -> invalid character '' in string literal, *json.SyntaxError
    

    【讨论】:

      猜你喜欢
      • 2013-12-05
      • 1970-01-01
      • 2018-01-17
      • 2012-01-06
      • 2019-03-17
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多