Created
March 19, 2018 19:50
-
-
Save olivere/b285ce788a4eeca24626c9bd3d699df1 to your computer and use it in GitHub Desktop.
Testing with Elastic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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