Tech behind Tech

Raw information. No finesse :)

Testing Clojure Code – Awesome “are”

with 2 comments


test-is a great library for testing clojure. Thanks to Philippe, I recently discover “are” in test-is. This is most underrated/underused macro in test-is library.

Lets take an example, where I want to test a function given a date, it will return end of month.

Without are,

(deftest test-end-of-month
        (is (= "2010-01-31 23:59" (end-of-month "2010-01-03 01:12")))
        (is (= "2010-01-31 23:59" (end-of-month "2010-01-03 21:59")))
        (is (= "2010-02-28 23:59" (end-of-month "2011-02-03 13:01")))
        (is (= "2016-02-29 23:59" (end-of-month "2016-02-03 03:01")))
        (is (= "2011-04-30 23:59" (end-of-month "2011-04-03 00:02"))))

With are,

(deftest test-end-of-month
        (are [expected ts] (= expected (end-of-month ts))

             "2010-01-31 23:59" "2010-01-03 01:12"
             "2010-01-31 23:59" "2010-01-03 21:59"
             "2011-02-28 23:59" "2011-02-03 13:01"
             "2016-02-29 23:59" "2016-02-03 03:01"
             "2011-04-30 23:59" "2011-04-03 00:02"))

The version without “are” has, so many duplications. It is difficult to read as it is cluttered. The version with “are” is easy to read, and it is so easy to add more test cases without much duplication.

Thanks Philippe for introducing me to wonders of “are”.

Written by Siva Jagadeesan

October 19, 2010 at 12:55 pm

Posted in Clojure

Tagged with , ,

2 Responses

Subscribe to comments with RSS.

  1. This is neat. But the documentation for ‘are’ says it may break error messages (line number reporting). Still worth it?

    Shantanu Kumar

    October 19, 2010 at 1:08 pm

    • Yah Shantanu, I think it is worth it.

      In fact, when it fails, it shows exactly which case failed.

      expected: (= "2016-02-29 23:59" (date-to-string (end-of-month (date-from-string "2016-01-03 03:01"))))
      actual: (not (= "2016-02-29 23:59" "2016-01-31 23:59"))

      Siva Jagadeesan

      October 19, 2010 at 2:00 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 146 other followers

%d bloggers like this: