with-redefs-fn

clojure.core

  • (with-redefs-fn binding-map func)
Temporarily redefines Vars during a call to func. Each val of
binding-map will replace the root value of its key which must be
a Var. After func is called with no args, 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.

2 Examples top

  • (ns http)
    
    (defn post [url]
      {:body "Hello world"})
    
    (ns app
      (:require [clojure.test :refer [run-tests]]))
    
    (deftest is-a-fn
      (with-redefs-fn {#'http/post (fn [url] {:body "Hello world again"})}
        #(is (= {:body "Hello world again"} (http/post "http://service.com/greet")))))
    
    (run-tests) ;; test is passing
  • => (defn f [] false)
    
    => (println (f))
    ;; false
    
    => (with-redefs-fn {#'f (fn [] true)} 
         #(println (f)))
    ;; true
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:6467 top

(defn with-redefs-fn
  "Temporarily redefines Vars during a call to func.  Each val of
  binding-map will replace the root value of its key which must be
  a Var.  After func is called with no args, 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"}
  [binding-map func]
  (let [root-bind (fn [m]
                    (doseq [[a-var a-val] m]
                      (.bindRoot ^clojure.lang.Var a-var a-val)))
        old-vals (zipmap (keys binding-map)
                         (map deref (keys binding-map)))]
    (try
      (root-bind binding-map)
      (func)
      (finally
        (root-bind old-vals)))))
Vars in clojure.core/with-redefs-fn:
Used in 0 other vars

Comments top

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