Improves MatchJSON error message
When one of the actual or expected cannot be parsed as JSON, it
would be quite nice to know quickly which one you, kind developer,
should be looking at in order to improve and fix your tests.
This commit mostly just adds the words "expected" and "actual"
around the error messages, which is hopefully more clear.
diff --git a/matchers/match_json_matcher.go b/matchers/match_json_matcher.go
index efc5e15..86b1ca6 100644
--- a/matchers/match_json_matcher.go
+++ b/matchers/match_json_matcher.go
@@ -4,8 +4,9 @@
"bytes"
"encoding/json"
"fmt"
- "github.com/onsi/gomega/format"
"reflect"
+
+ "github.com/onsi/gomega/format"
)
type MatchJSONMatcher struct {
@@ -50,11 +51,11 @@
ebuf := new(bytes.Buffer)
if err := json.Indent(abuf, []byte(actualString), "", " "); err != nil {
- return "", "", err
+ return "", "", fmt.Errorf("Actual '%s' should be valid JSON, but it is not.\nUnderlying error:%s", actualString, err)
}
if err := json.Indent(ebuf, []byte(expectedString), "", " "); err != nil {
- return "", "", err
+ return "", "", fmt.Errorf("Expected '%s' should be valid JSON, but it is not.\nUnderlying error:%s", expectedString, err)
}
return abuf.String(), ebuf.String(), nil
diff --git a/matchers/match_json_matcher_test.go b/matchers/match_json_matcher_test.go
index c1924ba..1fbf151 100644
--- a/matchers/match_json_matcher_test.go
+++ b/matchers/match_json_matcher_test.go
@@ -25,15 +25,21 @@
})
})
- Context("when either side is not valid JSON", func() {
- It("should error", func() {
+ Context("when the expected is not valid JSON", func() {
+ It("should error and explain why", func() {
+ success, err := (&MatchJSONMatcher{JSONToMatch: `{}`}).Match(`oops`)
+ Ω(success).Should(BeFalse())
+ Ω(err).Should(HaveOccurred())
+ Ω(err.Error()).Should(ContainSubstring("Actual 'oops' should be valid JSON"))
+ })
+ })
+
+ Context("when the actual is not valid JSON", func() {
+ It("should error and explain why", func() {
success, err := (&MatchJSONMatcher{JSONToMatch: `oops`}).Match(`{}`)
Ω(success).Should(BeFalse())
Ω(err).Should(HaveOccurred())
-
- success, err = (&MatchJSONMatcher{JSONToMatch: `{}`}).Match(`oops`)
- Ω(success).Should(BeFalse())
- Ω(err).Should(HaveOccurred())
+ Ω(err.Error()).Should(ContainSubstring("Expected 'oops' should be valid JSON"))
})
})