这是我的情况:
func TestGoogleAccountRepository_FindByClientCustomerIds(t *testing.T) {
type args struct {
ids []int
}
tests := []struct {
name string
args args
want []cedar.GoogleAccount
wantErr bool
}{
{
name: "should get client customer ids correctly",
args: args{ids: []int{9258066191}},
want: make([]cedar.GoogleAccount, 0),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := googleAccountRepo.FindByClientCustomerIds(tt.args.ids)
if (err != nil) != tt.wantErr {
t.Errorf("GoogleAccountRepository.FindByClientCustomerIds() error = %v, wantErr %v", err, tt.wantErr)
return
}
fmt.Printf("got = %#v, want = %#v\n", got, tt.want)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("GoogleAccountRepository.FindByClientCustomerIds() = %+v, want %+v", got, tt.want)
}
})
}
}
当我第一次运行这个测试时,我收到以下消息:
load env vars from local fs env file
=== RUN TestGoogleAccountRepository_FindByClientCustomerIds
--- FAIL: TestGoogleAccountRepository_FindByClientCustomerIds (0.62s)
=== RUN TestGoogleAccountRepository_FindByClientCustomerIds/should_get_client_customer_ids_correctly
got = []cedar.GoogleAccount(nil), want = []cedar.GoogleAccount{}
--- FAIL: TestGoogleAccountRepository_FindByClientCustomerIds/should_get_client_customer_ids_correctly (0.62s)
googleAccount_test.go:64: GoogleAccountRepository.FindByClientCustomerIds() = [], want []
FAIL
请注意此消息:
GoogleAccountRepository.FindByClientCustomerIds() = [], want []
got 和 want 似乎都是空的 slice,对吧?不,在我添加以下代码后:
fmt.Printf("got = %#v, want = %#v\n", got, tt.want)
打印出来:
got = []cedar.GoogleAccount(nil), want = []cedar.GoogleAccount{}
如您所见,got 的深度不等于 want。
那是因为我在googleAccountRepo.FindByClientCustomerIds 方法中声明了googleAccounts 变量,如下所示:
var googleAccounts []cedar.GoogleAccount
我改成之后
var googleAccounts = make([]cedar.GoogleAccount, 0)
测试通过:
=== RUN TestGoogleAccountRepository_FindByClientCustomerIds
--- PASS: TestGoogleAccountRepository_FindByClientCustomerIds (0.46s)
=== RUN TestGoogleAccountRepository_FindByClientCustomerIds/should_get_client_customer_ids_correctly
got = []cedar.GoogleAccount{}, want = []cedar.GoogleAccount{}
--- PASS: TestGoogleAccountRepository_FindByClientCustomerIds/should_get_client_customer_ids_correctly (0.46s)
PASS
Process finished with exit code 0