dict: deal with unknown keys
This commit is contained in:
parent
baff9ee722
commit
fc67cf14ff
@ -1,11 +1,15 @@
|
||||
package dictionary
|
||||
|
||||
import "errors"
|
||||
|
||||
type Dictionary map[string]string
|
||||
|
||||
func (d Dictionary) Search(word string) string {
|
||||
var ErrNotFound = errors.New("could not find the word you were looking for")
|
||||
|
||||
func (d Dictionary) Search(word string) (string, error) {
|
||||
result, ok := d[word]
|
||||
if !ok {
|
||||
return ""
|
||||
return "", ErrNotFound
|
||||
}
|
||||
return result
|
||||
return result, nil
|
||||
}
|
||||
|
@ -13,8 +13,20 @@ func assertStrings(t testing.TB, got, want string) {
|
||||
func TestSearch(t *testing.T) {
|
||||
dictionary := Dictionary{"test": "this is just a test"}
|
||||
|
||||
got := dictionary.Search("test")
|
||||
t.Run("known word", func(t *testing.T) {
|
||||
got, _ := dictionary.Search("test")
|
||||
want := "this is just a test"
|
||||
|
||||
assertStrings(t, got, want)
|
||||
})
|
||||
|
||||
t.Run("unknown word", func(t *testing.T) {
|
||||
_, err := dictionary.Search("undefined")
|
||||
want := "could not find the word you were looking for"
|
||||
if err == nil {
|
||||
t.Fatal("expected to get an error")
|
||||
}
|
||||
|
||||
assertStrings(t, err.Error(), want)
|
||||
})
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user