I just recently started working on a database-heavy Clojure application and am attempting to get some unit tests in place. Ideally, I'd like to avoid actually hitting a real database by mocking things out.
Here's an example of a simple test:
test-core.clj
(deftest core-test
(is (> (count (fn-under-test "foo")) 0)))
core.clj
(defn fn-under-test [slug]
(db/query "select * from %1" slug))
db.clj
(defn query [q & args]
(sql/with-connection db
(sql/with-query-results res
[(clause q args)]
(doall res))))
My question: is there a way, from within test-core.clj, to bind a custom function to 'db/query' such that core.clj will use it, as opposed to the definition within db.clj?
Thanks!
You can use binding to try and override db/query, but you'll need to define the namespace and var first. The easiest way is to import the db.clj into the same namespace and then use bindings.
(ns test-core
(:use clojure.test)
(:require db))
(deftest core-test
(binding [db/query (fn [query & args] (comment return some value here))]
(is (> (count (fn-under-test "foo")) 0))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With