Skip to content

Instantly share code, notes, and snippets.

@alexanderjamesking
Last active April 28, 2018 10:07
Show Gist options
  • Save alexanderjamesking/70f3bbfe3874de965e437306bbd9847c to your computer and use it in GitHub Desktop.
Save alexanderjamesking/70f3bbfe3874de965e437306bbd9847c to your computer and use it in GitHub Desktop.
(require '[clojure.test :refer [is]])
(defn random-beatle []
(case (rand-int 4)
0 "John"
1 "Paul"
2 "George"
3 "Ringo"))
(defn hello-beatle []
(str "Hello " (random-beatle)))
(with-redefs [random-beatle (fn [] "Alex")]
(is (= "Hello Alex" (hello-beatle))))
;; but be careful - this doesn't always work as you may expect
;; it depends on where the future is dereferenced
(is (= "Hello Alex" @(with-redefs [random-beatle (fn [] "Alex")]
(future (hello-beatle)))))
FAIL in () (form-init6579728494720041389.clj:204)
expected: (= "Hello Alex" (clojure.core/deref
(with-redefs [random-beatle (fn [] "Alex")]
(future (hello-beatle)))))
actual: (not (= "Hello Alex" "Hello Paul"))
;; but it works when the future is dereferenced inside with-redefs
(is (= "Hello Alex" (with-redefs [random-beatle (fn [] "Alex")]
@(future (hello-beatle)))))
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment