我在 Go 中構建了一個快速簡單的 API 來查詢 ElasticSearch。現在我知道它可以完成,我想通過添加測試來正確地完成它。我已經抽象了我的一些代碼,以便它可以進行單元測試,但是我在模擬彈性庫時遇到了一些問題,因此我認為最好嘗試一個簡單的案例來模擬它。import ( "encoding/json" "github.com/olivere/elastic" "net/http")...func CheckBucketExists(name string, client *elastic.Client) bool { exists, err := client.IndexExists(name).Do() if err != nil { panic(err) } return exists}而現在測試... import ( "fmt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "testing" )type MockClient struct { mock.Mock } func (m *MockClient) IndexExists(name string) (bool, error) { args := m.Mock.Called() fmt.Println("This is a thing") return args.Bool(0), args.Error(1) } func TestMockBucketExists(t *testing.T) { m := MockClient{} m.On("IndexExists", "thisuri").Return(true)>> r := CheckBucketExists("thisuri", m) assert := assert.New(t) assert.True(r, true) }我因以下錯誤而屈服:cannot use m (type MockClient) as type *elastic.Client in argument to CheckBucketExists.我假設這是我使用 elastic.client 類型的基礎,但我仍然是個菜鳥。
- 2 回答
- 0 關注
- 165 瀏覽
添加回答
舉報
0/150
提交
取消