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

标签 unit-testing go

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

测试

声明如下:

// 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/

相关文章:

memory - 为什么 `[0]byte` 在结构中的位置很重要?

r - 需要安装Go才能使用Academic Hugo主题的blogdown

java - 责任链模式

java - Spring 启动1.5.4 : exclude configuration class in unit test

go - 找不到模板文件

去大内存垃圾回收性能

javascript - 如何模拟回调函数以测试其位于另一个函数的参数内

python - 如何在 Buildout 中对我的 Python 代码运行单元测试?

unit-testing - 单元测试调用另一个方法的方法

go - Go 运行时如何检查 goroutine 是否被阻塞?