Skip to content

Instantly share code, notes, and snippets.

@olivere
Created March 19, 2018 19:50
Show Gist options
  • Save olivere/b285ce788a4eeca24626c9bd3d699df1 to your computer and use it in GitHub Desktop.
Save olivere/b285ce788a4eeca24626c9bd3d699df1 to your computer and use it in GitHub Desktop.
Testing with Elastic
package esi
import (
"context"
"github.com/olivere/elastic"
)
type BusinessLogic struct {
s Searcher
}
func (bl *BusinessLogic) Search() (*elastic.SearchResult, error) {
return bl.s.Do(context.TODO())
}
package esi
import (
"context"
"testing"
"github.com/olivere/elastic"
)
func TestBusinessLogic(t *testing.T) {
mock := &MockSearcher{}
mock.OnDo = func(_ context.Context) (*elastic.SearchResult, error) {
return &elastic.SearchResult{}, nil
}
//
bl := &BusinessLogic{
s: mock,
}
res, err := bl.Search()
if err != nil {
t.Fatal(err)
}
if res == nil {
t.Fatal("expected search result")
}
}
package esi
import (
"context"
"github.com/olivere/elastic"
)
// Notice that *elastic.SearchService implements the Searcher interface!
type Searcher interface {
Do(ctx context.Context) (*elastic.SearchResult, error)
}
package esi
import (
"context"
"github.com/olivere/elastic"
)
var (
// Compile-time error when *MockServer doesn't implement Searcher interface
_ Searcher = (*MockSearcher)(nil)
)
type MockSearcher struct {
OnDo func(ctx context.Context) (*elastic.SearchResult, error)
}
func (s *MockSearcher) Do(ctx context.Context) (*elastic.SearchResult, error) {
return s.OnDo(ctx)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment