测试 assert.Equal,除了一个字段之外。

huangapple go评论72阅读模式
英文:

Testing assert.Equal except one field

问题

我正在为在数据库中读写结构体的测试编写代码,其中一个字段是一个在数据库中自动计算的时间戳。因此,当我写入结构体时,它的时间戳为0,但当我从数据库中读取时,时间戳会有一个实际值。

我想比较这两个值,但忽略自动计算的字段。这种操作是否可行?

英文:

I'm writing a test for reading/writing a struct in a DB and one of its fields is a timestamp which is auto-calculated in the DB. So when I write the struct its timestamp is 0 but when I read it from the DB the timestamp has an actual value.

I want to compare the two values but to ignore the auto-calculated field. Is it possible?

答案1

得分: 3

在进行测试之前,设置其他的"except"字段:

now := time.Now()
expected := SomeStruct{
    ID:       123,
    Name:     "Test",
    Timestamp: now,
    ...
}
result, _ := db.Select(....)
result.Timeestamp = now
if !reflect.DeepEqual(result, expected) {
   ...
}
英文:

Set the other "except" field prior to testing:

now := time.Now()
expected := SomeStruct{
    ID:       123,
    Name:     "Test",
    Timestamp: now,
    ...
}
result, _ := db.Select(....)
result.Timeestamp = now
if !reflect.DeepEqual(result, expected) {
   ...
}

答案2

得分: 1

你可以使用 cmpopts 包IgnoreFields 函数来轻松实现这一点。

以下是一个示例:

got, want := FuncUnderTest()

if !cmp.Equal(want, got, cmpopts.IgnoreFields(YourStruct{}, "FieldName")) {
    t.Errorf("FuncUnderTest() 不匹配")
}
英文:

You can easily do this by using IgnoreFields function of the cmpopts package.

Here's an example:

got, want := FuncUnderTest()

if !cmp.Equal(want, got, cmpopts.IgnoreFields(YourStruct{}, "FieldName")) {
	t.Errorf("FuncUnderTest() mismatch")
}

huangapple
  • 本文由 发表于 2017年7月13日 21:36:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/45082301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定