Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure database unit testing / mocking

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!

like image 544
eff Avatar asked Jul 22 '11 21:07

eff


1 Answers

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))))
like image 173
Jeff Avatar answered Sep 28 '22 19:09

Jeff