Testing in Clojure (Part-1: Unit testing)

Table of contents
Reading Time: 3 minutes

Testing a web application in Clojure is as important as testing in any other language. Clojure testing has been made simpler with its built in unit tests.

This blog explains about how to do unit testing(testing each module independently) of Clojure methods with some very basic syntax.

For Clojure testing we would be using a clojure.test testing namespace to load testing framework for placing the midje framework test cases.

Firstly, add the following dependencies and plugins of Midje testing framework in your project.clj file:

testing framework gives you choice from using any of the two test defining methods:

  1. defining test using with-test followed by method defination and test case.

2. or defining your test cases in a seperate file using deftest macro(test function with no arguments) which improves the code quality.

Example: create two separate files-


methodTest.clj (Test file)

below namespace definition also requires importing the namespace of the file where the methods to be tested are defined followed by :refer :all for refering to every method in this namespace. Noir.util.test is required only to test those methods which uses clojure noir library validation checks.

(for leiningen clojure framework we are using lein test command in terminal within project name path to run the test.)

Another example test case for testing validation method :

output: first assertion shows true with no error message, rest 2 assertion gives described error message and failure test case

Example Test case for testing nested method by unit testing method

output: shows true result with no error message as the same data exists in database for “username”


*(is) in above test cases checks a single instance of method and throws exception if   fails.Multiple assertions can also be checked within a single method by just defining multiple arguments and not same method again and again using(are).

*lein test command runs all tests in all namespaces. One can test the test cases under a single namespace also using lein test ‘your.namespace’.

Written by 

Joseph Ross is a Principal Consultant at Knoldus Inc. having more than 10 years of experience. Joseph has a passion for identifying challenges and give impactful solutions to the clients. He is a football fan and loves to watch TV series. Joseph has a cross-functional business operations and technology consulting experience. Joseph is familiar with programming languages such as Scala, C++, Java, CSS and HTML.