Skip to content

Instantly share code, notes, and snippets.

@Kungi
Created February 29, 2016 11:17
Show Gist options
  • Save Kungi/1e1b396db629272749b6 to your computer and use it in GitHub Desktop.
Save Kungi/1e1b396db629272749b6 to your computer and use it in GitHub Desktop.
fn-called simple mocking
(ns clj-demgen.util.fn-called
(:require [clojure.test :as t :refer [is deftest]]))
(defn fn-called? [f thunk]
(let [called (atom false)]
(with-redefs-fn {f (fn [& args]
(reset! called true))}
thunk)
@called))
(defmacro is-fn-called? [f & body]
`(is (fn-called? ~(resolve f)
(fn [] ~@body))
~(str "Function `" f "` not called")))
(defn fn-called-with-args? [f thunk checks-thunk]
(let [called (atom false)
f-args (atom [])]
(with-redefs-fn {f (fn [& args]
(reset! called true)
(reset! f-args args))}
thunk)
(if @called
(apply checks-thunk @f-args))
@called))
(defmacro is-fn-called-with-args? [f args arg-checks & body]
`(is (fn-called-with-args? ~(resolve f)
(fn [] ~@body)
(fn ~args ~@arg-checks))
~(str "Function `" f "` not called")))
(defn log [s]
(println s))
#_(deftest fn-called-test
(is-fn-called? log (log "Foo")))
#_(deftest fn-called-with-args-test
(is-fn-called-with-args? log
[s]
[(is (= s "Bar?"))]
(log "Foo!")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment