Skip to content

Instantly share code, notes, and snippets.

@ulises
Created February 14, 2014 11:29
Show Gist options
  • Save ulises/8999600 to your computer and use it in GitHub Desktop.
Save ulises/8999600 to your computer and use it in GitHub Desktop.
(defn mock [& {:keys [value delay log? wrap throw-after-count]}]
{:pre [(not (and value wrap))]}
(let [state (ref {:call-count 0
:call-args '()})]
(with-meta (fn [& args]
(do
(if log?
(log/info "Calling mock " (inc (:call-count @state))
" with " args))
(dosync
(alter state (fn [{:keys [call-count
call-args]}
args]
{:call-count (inc call-count)
:call-args (conj call-args args)})
args))
(when throw-after-count
(if (< (:call-count @state) throw-after-count)
(throw (Exception. "Mock threw!")))))
(when delay
(Thread/sleep delay))
(if value value (and wrap (apply wrap args))))
{:state state})))
(defn call-count
([mock]
(:call-count @(:state (meta mock))))
([mock & {:keys [delay]}]
(do (Thread/sleep delay)
(call-count mock))))
(defn call-args
([mock]
(:call-args @(:state (meta mock)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment