go测试用例中如何处理json语法错误?

发布于 2025-01-19 10:01:05 字数 652 浏览 2 评论 0原文

我正在测试一个场景,其中 json.Unmarshall 失败并返回

&json.SyntaxError{msg:"unexpected end of JSON input", Offset:0}

代码如下:

err = json.Unmarshal(input, &data)

if err != nil {
    return nil, err
}

测试用例期望出现这种类型的错误:

{
...
errorType: &json.SyntaxError{},
...
}

断言如下:

assert.Equal(t, tt.errorType, err)

由于错误消息不同而失败:

expected: &json.SyntaxError{msg:"", Offset:0}
actual  : &json.SyntaxError{msg:"unexpected end of JSON input", Offset:0}

我该如何处理这个问题?也许利用 Error()

I'm testing a scenario where json.Unmarshall fails and returns

&json.SyntaxError{msg:"unexpected end of JSON input", Offset:0}

the code is like this:

err = json.Unmarshal(input, &data)

if err != nil {
    return nil, err
}

test case is expecting this type of error:

{
...
errorType: &json.SyntaxError{},
...
}

the assertion is like this:

assert.Equal(t, tt.errorType, err)

which is failing because the error message is different:

expected: &json.SyntaxError{msg:"", Offset:0}
actual  : &json.SyntaxError{msg:"unexpected end of JSON input", Offset:0}

How can I handle this? Perhaps making use of Error() ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半窗疏影 2025-01-26 10:01:05

首先是不可能直接制作此哨兵错误:

_ = &json.SyntaxError{msg: "unexpected end of JSON input", Offset: 0}  // msg field is not exported

您可以最接近的是检查错误类型。要执行此操作 errors.as

var tt *json.SyntaxError

if errors.As(err, &tt) {
    log.Printf("Syntax Error: %v", tt)
} else if err != nil {
    log.Fatalf("Fatal: %#v", err)
}

https://go.dev/play/p/mlqgn2ppwbs

您可以检查offset,因为这是公共字段。但是要比较非公共msg字段,您需要使用err.error() - 但这可能是脆弱的,因为措辞可能会随着时间的推移而变化


注意: errors.is 在这里无法使用,因为它仅测试错误平等:直接;或通过 error.unwrap -ing。

因为 json.syntaxerror在这里未包装 - 也不是 sentinel ofor - 无法通过errors.is匹配。

Firstly it's not possible to craft this sentinel error directly:

_ = &json.SyntaxError{msg: "unexpected end of JSON input", Offset: 0}  // msg field is not exported

the closest you can come is to check for the error type. To do this use errors.As

var tt *json.SyntaxError

if errors.As(err, &tt) {
    log.Printf("Syntax Error: %v", tt)
} else if err != nil {
    log.Fatalf("Fatal: %#v", err)
}

https://go.dev/play/p/mlqGN2ypwBs

You can check the Offset as that is public field. But to compare the non-public msg field, you'd need to use err.Error() - but this may be brittle as wording may change over time.


Note: errors.Is cannot be used here, as it only tests error equality: directly; or via error.Unwrap-ing.

Since the json.SyntaxError here is not wrapped - nor is it a sentinel error - it cannot be matched via errors.Is.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文