(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.
(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
(defn add-5 [n] (+ n 5))
(with-redefs-fn {#'add-5 (fn [n] (+ n 50))}
#(is (= 60 (add-5 10))))
;; Cannot redefine the reference in the partial function
(def partial-add-5 (partial add-5))
(with-redefs-fn {#'add-5 (fn [n] (+ n 50))}
#(is (= 15 (partial-add-5 10))))