Search code examples
clojuresqlkormaspeclj

How do I mock sqlKorma?


I am unfamiliar with how mocking works within Clojure. Specifically, I am unsure about how I should test a function which implements a sqlKorma query or call to the database? I would ideally like to be able to mock sqlKorma in my tests.

(defn fetch [id]
(->
    (korma/select* :my-table)
    (korma/where {:id id})
    (korma/exec)))

(defn retrieve [id]
  (->
    (fetch id)
    (ring/response)))

I am using Speclj to test my application.

(describe "item"
      (it "is fetched"
          (let [fetched (fetch :test-case)] ;here I want to be able to mock sqlKorma and return an array of 1.
          (should= (count fetch) 1)))

      (it "is retrieved"
          (let [retrieved (retrieve :test-case)]
          (should= (get retrieved :status) 200))))

Solution

  • There are several ways. One way is to use a different database for testing. E.g. an H2 in memory database. This is preferred since you don't need mocking and you test your SQL as well. If you really still want to mock your fetch function, you could use with-redefs:

    (defn foo [] [{:foo "bar"}])
    (foo) ;;=> [{:foo "bar"}]
    (with-redefs [foo (fn [] [{:something "else"}])] (foo))
     ;;=> [{:something "else"}]
    (foo) ;;=> [{:foo "bar"}]
    

    https://clojuredocs.org/clojure.core/with-redefs