Over a million developers have joined DZone.

Clojure: expectations & with-redefs

DZone's Guide to

Clojure: expectations & with-redefs

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

In general, when I'm writing tests, the pure functions end up as bare expects and the impure functions end up as scenarios. The following contrived namespace keeps a list of users and allows you to get the full name of each user.

(ns user)

(def users (atom #{}))

(defn full-name [{:keys [fname lname]}] (str fname " " lname))

(defn all-names [] (map full-name @users))

The tests for this namespace would often look something like the following code:

(ns user-expectations
  (:use expectations user))

(expect "John Dory" (full-name {:fname "John" :lname "Dory"}))

(ns user-expectations.scenarios
  (:use expectations.scenarios user))

  (with-redefs [users (atom #{{:fname "Mary", :lname "Dory"} {:fname "John", :lname "Dory"}})]
    (expect ["Mary Dory" "John Dory"] (all-names))))

It feels natural to put the with-redefs in a scenario, since scenarios also support (and often make use of) stubbing, localize-state, & freeze-time. However, there's really no reason that you need to use a scenario if you're simply looking to redef a var.

The following test provides the same level of functionality verification, without needing to use expectations.scenarios: 

(ns user-expectations
  (:use expectations user))

(expect "John Dory" (full-name {:fname "John" :lname "Dory"}))

(expect ["Mary Dory" "John Dory"]
  (with-redefs [users (atom #{{:fname "Mary", :lname "Dory"} {:fname "John", :lname "Dory"}})]

scenarios are great, but these days I try to keep things simple with bare expectations whenever possible.


Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}