Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit-testing side-effects in Clojure

I have a function that pulls messages from an AMPQ message bus:

(defn get-message [queue client]
    (let [msg (mq/get-message client queue)]
    (if msg
        (logit msg))))

mq/get-message and logit are both side-effects, one depends on network access, the other on disk IO on the local machine.

Is there an idiomatic way of unit-testing side-effects in Clojure? My first thought was mocks/stubs, but if there was something better.

like image 962
Allyl Isocyanate Avatar asked Jan 12 '23 03:01

Allyl Isocyanate


1 Answers

Using core.test I usually go the way of mocking up the side effectish functions using with-redefs

(deftest ampq-messaing
  "Test messaging"
  (let [logit-msg (atom nil)]
    (with-redefs [mq/get-message (fn [] "message")
                  logit (fn [msg] 
                           (reset! logit-msg msg))]
      (let [response (your-test-trigger)]
        (is (= "message" @logit-msg))))))

In that case I'm testing the returned message from mq is the one used in logit, and I'm assuming that your-test-trigger is something that triggers a call to get-message.

like image 104
guilespi Avatar answered Jan 13 '23 17:01

guilespi