Skip to content

Instantly share code, notes, and snippets.

@mbuczko
Last active October 22, 2019 12:12
Show Gist options
  • Save mbuczko/427447ceefcffd6386bd9bba47850a54 to your computer and use it in GitHub Desktop.
Save mbuczko/427447ceefcffd6386bd9bba47850a54 to your computer and use it in GitHub Desktop.
clojure / make-mock
(defmacro with-mock [vr & body]
`(with-redefs [~vr (with-meta
(fn [& ~'args] (swap! (-> ~vr meta :args) conj ~'args))
{:args (atom [])})]
(do ~@body)))
(defmacro make-mock
([m] `(make-mock ~m nil))
([m stub]
`(with-meta
(fn [& ~'args]
(swap! (-> ~m meta :args) conj ~'args)
; If stub is a function, execute it
(if (fn? ~stub)
(apply ~stub ~'args)
~stub))
{:args (atom [])})))
(defn gen-redefs [[m stub & spec]]
(into
[m `(make-mock ~m ~stub)]
(when spec
(gen-redefs spec))))
(defn calls [m] @(-> m meta :args))
(defn last-call [m] (last (calls m)))
(defn called? [m] (not-empty (calls m)))
(defn call-count [m] (-> m calls count))
(defn reset-calls! [m] (reset! (:args (meta m)) []))
(defmacro with-mock [specs & body]
`(with-redefs ~(gen-redefs specs)
(do ~@body)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment