with-redefs

clojure.core

  • (with-redefs bindings & body)
binding => var-symbol temp-value-expr

Temporarily redefines Vars while executing the body. The
temp-value-exprs will be evaluated and each resulting value will
replace in parallel the root value of its Var. After the body is
executed, the root values of all the Vars will be set back to their
old values. These temporary changes will be visible in all threads.
Useful for mocking out functions during testing.

3 Examples top

  • user=> [(type []) (class [])]
    [clojure.lang.PersistentVector clojure.lang.PersistentVector]
    
    user=> (with-redefs [type (constantly java.lang.String)
                         class (constantly 10)]
             [(type [])
              (class [])])
    [java.lang.String 10]
  • (ns http)
    
    (defn post [url]
      {:body "Hello world"})
    
    (ns app
      (:require [clojure.test :refer [deftest is run-tests]]))
    
    (deftest is-a-macro
      (with-redefs [http/post (fn [url] {:body "Goodbye world"})]
        (is (= {:body "Goodbye world"} (http/post "http://service.com/greet")))))
    
    (run-tests) ;; test is passing
  • ;; be careful, with-redefs can permanently change a var if applied concurrently:
    
    user> (defn ten [] 10)
    #'user/ten
    user> (doall (pmap #(with-redefs [ten (fn [] %)] (ten)) (range 20 100)))
    ...
    user> (ten)
    79
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:6487 top

(defmacro with-redefs
  "binding => var-symbol temp-value-expr

  Temporarily redefines Vars while executing the body.  The
  temp-value-exprs will be evaluated and each resulting value will
  replace in parallel the root value of its Var.  After the body is
  executed, the root values of all the Vars will be set back to their
  old values.  These temporary changes will be visible in all threads.
  Useful for mocking out functions during testing."
  {:added "1.3"}
  [bindings & body]
  `(with-redefs-fn ~(zipmap (map #(list `var %) (take-nth 2 bindings))
                            (take-nth 2 (next bindings)))
                    (fn [] ~@body)))
Vars in clojure.core/with-redefs:
Used in 0 other vars

Comments top

No comments for with-redefs. Log in to add a comment.