Clojure test stubbing


/ Published in: Clojure
Save to your folder(s)

Macro allowing for substitution of functions with predefined values.
Taken from "Clojure in action" page 180
Example:
(defn calc-x [x1 x2]
(* x1 x2))
(defn calc-y [y1 y2]
(/ y2 y1))
(defn some-client []
(println (calc-x 2 3) (calc-y 3 4)))
(stubbing [calc-x 1
calc-y 2
(some-client))

prints: "1 2" instead of "6 4/3"


Copy this code and paste it in your HTML
  1. (defmacro stubbing [stub-forms & body]
  2. (let [stub-pairs (partition 2 stub-forms)
  3. returns (map last stub-pairs)
  4. stub-fns (map #(list 'constantly %) returns)
  5. real-fns (map first stub-pairs)]
  6. `(binding [~@(interleave real-fns stub-fns)]
  7. ~@body)))

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.