英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论