gpt4 book ai didi

unit-testing - Golang 中的编码/解码时间对象意外失败

转载 作者:IT王子 更新时间:2023-10-29 02:31:24 26 4
gpt4 key购买 nike

解码编码的时间对象失败,因为有几个字符

测试

声明如下:

// values
now := time.Now()
timeToJSON, _ := json.Marshal(now)
var obj time.Time
json.Unmarshal(timeToJSON, &obj)

然后做如下测试逻辑:

if !assert.Equal(t,
now.String(),
obj.String()) {
t.FailNow()
}

预期

要通过的测试,并且两个对象要相等

实际

失败了:

--- FAIL: TestFromJSON (0.00s)
D:\dev2017\GO\src\ezsoft\apiserver_sdk\model\delete\deleteModel_test.go:94:
Error Trace: deleteModel_test.go:94
Error: Not equal:
expected: "2018-09-04 10:36:18.3627338 -0400 EDT m=+0.014000801"
actual : "2018-09-04 10:36:18.3627338 -0400 EDT"

Diff:
--- Expected
+++ Actual
@@ -1 +1 @@
-2018-09-04 10:36:18.3627338 -0400 EDT m=+0.014000801
+2018-09-04 10:36:18.3627338 -0400 EDT
Test: TestFromJSON
FAIL
FAIL ezsoft/apiserver_sdk/model/delete 1.336s
Error: Tests failed.

注意

我注意到,在检查输出时,不知何故,一些 m=+[blah] 被附加到预期/实际。

我不知道为什么,但是,skimming RFC 3339没有给我任何提示。

最佳答案

time.String() 不是测试时间值的可靠方法(除非您也关心单调时钟值)。来自 the docs (强调已添加):

func (Time) String

func (t Time) String() string

String returns the time formatted using the format string

"2006-01-02 15:04:05.999999999 -0700 MST"

If the time has a monotonic clock reading, the returned string includes a final field "m=±", where value is the monotonic clock reading formatted as a decimal number of seconds.

The returned string is meant for debugging; for a stable serialized representation, use t.MarshalText, t.MarshalBinary, or t.Format with an explicit format string.

对于您的用例,最好使用 time.MarshalText() 的输出而不是 time.String():

expected, _ := now.MarshalText()
actual, _ := obj.MarshalText()

if !assert.Equal(string(expected), string(actual)) ...

关于unit-testing - Golang 中的编码/解码时间对象意外失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52168809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com