algoliasearch-client-go
algoliasearch-client-go copied to clipboard
`client.InitIndex` doesn't return `IndexInterface`
- Algolia Client Version: 3.4.0
- Language Version: 1.16.2
Description
I'd like to be able to do the following in test. I'm stubbing out the index to replace it with predictable, local behavior that doesn't actually connect to Algolia. I'm unable to do this because InitIndex
returns a *search.Index
instead of an IndexInterface
.
Steps To Reproduce
The error I get:
cannot use c (variable of type *mockClient) as clientInterfaceSubset value in argument to NewService: wrong type for method InitIndex (have func(indexName string) github.com/algolia/algoliasearch-client-go/v3/algolia/search.IndexInterface, want func(indexName string) *github.com/algolia/algoliasearch-client-go/v3/algolia/search.Index)compilerInvalidIfaceAssign
package main
import (
"testing"
"github.com/algolia/algoliasearch-client-go/v3/algolia/search"
)
// User code
type clientInterfaceSubset interface {
InitIndex(indexName string) *search.Index
}
type service struct {
client clientInterfaceSubset
}
func NewService(client clientInterfaceSubset) *service {
svc := &service{
client: client,
}
ind := client.InitIndex("test")
if _, err := ind.Exists(); err != nil {
panic(err)
}
return svc
}
// Test code
type mockClient struct{}
func (mc *mockClient) InitIndex(indexName string) search.IndexInterface {
return &mockIndex{}
}
type mockIndex struct {
*search.Index
}
func (mi *mockIndex) Exists() (bool, error) {
return true, nil
}
func TestClient(t *testing.T) {
c := &mockClient{}
svc := NewService(c)
_ = svc
}
Hello! Sorry for the delayed answer... I don't think the return value of .InitIndex()
must returns an interface. It's fine to return a concrete type. You can expect the index interface being returned from clientInterfaceSubset.InitIndex()
method. In this case the tests should pass and you can adapt the mock the way you want. Let me know if it helps!
type mockClient struct{}
func (mc *mockClient) InitIndex(indexName string) search.IndexInterface {
return &mockIndex{}
}
type mockIndex struct {
search.IndexInterface
}
func (mi *mockIndex) Exists() (bool, error) {
return true, nil
}