go测试用例中如何处理json语法错误?
我正在测试一个场景,其中 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先是不可能直接制作此哨兵错误:
您可以最接近的是检查错误类型。要执行此操作 errors.as
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:
the closest you can come is to check for the error type. To do this use errors.As
https://go.dev/play/p/mlqGN2ypwBs
You can check the
Offset
as that is public field. But to compare the non-publicmsg
field, you'd need to useerr.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
.