Clojure Unit Testing with Expectations Part Two
Clojure Unit Testing with Expectations Part Three (this entry)
Clojure Unit Testing with Expectations Part Four
Clojure Unit Testing with Expectations Part Five
Clojure Unit Testing with Expectations Part Six
I've previously written about verifying equality and the various non-equality expectations that are available. This entry will focus on another type of comparison that is allowed in expectations - verifying that an 'expected' value is in an 'actual' value.
A quick recap - expectations generally look like this: (expect expected actual)
verifying an expected value is in an actual value is straightforward and hopefully not a surprising syntax: (expect expected (in actual))
If that's not clear, these examples should make the concept completely clear.
;; expect a k/v pair in a map.As you would expect, running these expectations results in 3 passing tests.
(expect {:foo 1} (in {:foo 1 :cat 4}))
;; expect a key in a set
(expect :foo (in #{:foo :bar}))
;; expect a val in a list
(expect :foo (in [:foo :bar]))
jfields$ lein expectationsAs usual, I'll show the failures as well.
Ran 3 tests containing 3 assertions in 8 msecs
0 failures, 0 errors.
;; expect a k/v pair in a map.expectations does it's best to provide you with any additional info that might be helpful. In the case of the vector and the set there's not much else that can be said; however, the map failure gives you additional information that can be used to track down the issue.
(expect {:foo 2} (in {:foo 1 :cat 4}))
;; expect a key in a set
(expect :baz (in #{:foo :bar}))
;; expect a val in a list
(expect :baz (in [:foo :bar]))
jfields$ lein expectations
failure in (core.clj:18) : sample.test.core
(expect {:foo 2} (in {:foo 1, :cat 4}))
expected: {:foo 2}
in: {:foo 1, :cat 4}
:foo expected: 2
was: 1
failure in (core.clj:21) : sample.test.core
(expect :baz (in #{:foo :bar}))
key :baz not found in #{:foo :bar}
failure in (core.clj:24) : sample.test.core
(expect :baz (in [:foo :bar]))
value :baz not found in [:foo :bar]
There's nothing magical going on with 'in' expectations and you could easily do the equivalent with select-keys, contains?, or some, but expectations allows you to get that behavior while keeping your tests succinct.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.