Пишу тесты на слой repository с поднятием реальной БД(
https://testcontainers.com/) и столкнулся с проблемой при проверки структур, где есть time.Time.
Пример теста:
code
func (suite *PostgresSuite) TestColorPGRepoV1_GetByID() {
if testing.Short() {
suite.T().Skip("skipping test in short mode")
}
ctx := context.Background()
r := NewColorPGRepoV1(suite.pgContainer.GetPGPool())
testColor := testdata.GetColorCreate()
_, err := r.Create(ctx, testColor)
suite.Require().NoError(err, "failed to create color")
currentTime := time.Now().UTC()
type args struct {
ctx context.Context
id int64
}
tests := []struct {
name string
args args
expected *model.ColorSQL
expectErr bool
}{
{
name: "ok",
args: args{
ctx: ctx,
id: 1,
},
expected: &model.ColorSQL{
ID: 1,
Name: testColor.Name,
CreatedAt: currentTime,
UpdatedAt: currentTime,
DeletedAt: nil,
},
expectErr: false,
},
{
name: "not_found",
args: args{
ctx: ctx,
id: 123,
},
expected: nil,
expectErr: false,
},
}
for _, tt := range tests {
suite.Run(tt.name, func() {
suite.T().Logf("running test case: %s", tt.name)
color, err := r.GetByID(tt.args.ctx, tt.args.id)
if tt.expectErr {
suite.Error(err, "expected an error but got none")
suite.Nil(color, "expected category to be nil")
} else {
suite.NoError(err, "expected no error but got one")
if tt.expected != nil {
suite.Equal(tt.expected, color)
} else {
suite.Nil(color, "expected category to be nil")
}
}
})
}
}
Тест падает с ошибкой:
Error: Not equal:
expected: &model.ColorSQL{ID:1, Name:"Cullen Gerhold", CreatedAt:time.Date(2025, time.March, 15, 20, 50, 54, 823874100, time.UTC), UpdatedAt:time.Date(2025, time.March, 15, 20, 50, 54, 823874100, time.UTC), DeletedAt:<nil>}
actual : &model.ColorSQL{ID:1, Name:"Cullen Gerhold", CreatedAt:time.Date(2025, time.March, 15, 20, 50, 54, 822076000, time.UTC), UpdatedAt:time.Date(2025, time.March, 15, 20, 50, 54, 822076000, time.UTC), DeletedAt:<nil>}
Первое, что пришло в голову обновить код вот так:
code
if tt.expected != nil {
suite.Equal(tt.expected.ID, color.ID, "id mismatch")
suite.Equal(tt.expected.Name, color.Name, "name mismatch")
suite.WithinDuration(tt.expected.CreatedAt, color.CreatedAt, time.Second, "createdAt mismatch")
suite.WithinDuration(tt.expected.UpdatedAt, color.UpdatedAt, time.Second, "updatedAt mismatch")
suite.Equal(tt.expected.DeletedAt, color.DeletedAt, "deletedAt mismatch")
} else {
suite.Nil(color, "expected category to be nil")
}
Но если я буду обновлять структуру и добавлять новые поля, то если я забуду обновить мои тесты и запустить тесты, то они завершаться успешно, т.к новые поля не будут проверяться, как можно избежать эту ошибку?