DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Java
  4. Clojure: Mocking

Clojure: Mocking

Jay Fields user avatar by
Jay Fields
·
Sep. 02, 10 · Interview
Like (0)
Save
Tweet
Share
5.86K Views

Join the DZone community and get the full member experience.

Join For Free

An introduction to clojure.test is easy, but it doesn't take long before you feel like you need a mocking framework. As far as I know, you have 3 options.

  1. Take a look at Midje. I haven't gone down this path, but it looks like the most mature option if you're looking for a sophisticated solution.

  2. Go simple. Let's take an example where you want to call a function that computes a value and sends a response to a gateway. Your first implementation looks like the code below. (destructuring explained)
    (defn withdraw [& {:keys [balance withdrawal account-number]}]
     (gateway/process {:balance (- balance withdrawal)
                       :withdrawal withdrawal
                       :account-number account-number}))
    No, it's not pure. That's not the point. Let's pretend that this impure function is the right design and focus on how we would test it.

    You can change the code a bit and pass in the gateway/process function as an argument. Once you've changed how the code works you can test it by passing identity as the function argument in your tests. The full example is below.
    (ns gateway)
    
    (defn process [m] (println m))
    
    (ns controller
     (:use clojure.test))
    
    (defn withdraw [f & {:keys [balance withdrawal account-number]}]
     (f {:balance (- balance withdrawal)
         :withdrawal withdrawal
         :account-number account-number}))
    
    (withdraw gateway/process :balance 100 :withdrawal 22 :account-number 4)
    ;; => {:balance 78, :withdrawal 22, :account-number 4}
    
    (deftest withdraw-test
     (is (= {:balance 78, :withdrawal 22, :account-number 4}
      (withdraw identity :balance 100 :withdrawal 22 :account-number 4))))
    
    (run-all-tests #"controller")
    If you run the previous example you will see the println output and the clojure.test output, verifying that our code is working as we expected. This simple solution of passing in your side effect function and using identity in your tests can often obviate any need for a mock.

  3. Solution 2 works well, but has the limitations that only one side-effecty function can be passed in and it's result must be used as the return value.

    Let's extend our example and say that we want to log a message if the withdrawal would cause insufficient funds. (Our gateway/process and log/write functions will simply println since this is only an example, but in production code their behavior would differ and both would be required)
    (ns gateway)
    
    (defn process [m] (println "gateway: " m))
    
    (ns log)
    
    (defn write [m] (println "log: " m))
    
    (ns controller
      (:use clojure.test))
    
    (defn withdraw [& {:keys [balance withdrawal account-number]}]
      (let [new-balance (- balance withdrawal)]
        (if (> 0 new-balance)
          (log/write "insufficient funds")
          (gateway/process {:balance new-balance
                            :withdrawal withdrawal
                            :account-number account-number}))))
    
    (withdraw :balance 100 :withdrawal 22 :account-number 4)
    ;; => gateway:  {:balance 78, :withdrawal 22, :account-number 4}
    
    (withdraw :balance 100 :withdrawal 220 :account-number 4)
    ;; => log:  insufficient funds
    Our new withdraw implementation calls two functions that have side effects. We could pass in both functions, but that solution doesn't seem to scale very well as the number of passed functions grows. Also, passing in multiple functions tends to clutter the signature and make it hard to remember what is the valid order for the arguments. Finally, if we need withdraw to always return a map showing the balance and withdrawal amount, there would be no easy solution for verifying the string sent to log/write.

    Given our implementation of withdraw, writing a test that verifies that gateway/process and log/write are called correctly looks like a job for a mock. However, thanks to Clojure's binding function, it's very easy to redefine both of those functions to capture values that can later be tested.

    The following code rebinds both gateway/process and log/write to partial functions that capture whatever is passed to them in an atom that can easily be verified directly in the test.
    (ns gateway)
    
    (defn process [m] (println "gateway: " m))
    
    (ns log)
    
    (defn write [m] (println "log: " m))
    
    (ns controller
      (:use clojure.test))
    
    (defn withdraw [& {:keys [balance withdrawal account-number]}]
      (let [new-balance (- balance withdrawal)]
        (if (> 0 new-balance)
          (log/write "insufficient funds")
          (gateway/process {:balance new-balance
                            :withdrawal withdrawal
                            :account-number account-number}))))
    
    (deftest withdraw-test
      (let [result (atom nil)]
        (binding [gateway/process (partial reset! result)]
          (withdraw :balance 100 :withdrawal 22 :account-number 4)
          (is (= {:balance 78, :withdrawal 22, :account-number 4} @result)))))
    
    (deftest withdraw-test
      (let [result (atom nil)]
        (binding [log/write (partial reset! result)]
          (withdraw :balance 100 :withdrawal 220 :account-number 4)
          (is (= "insufficient funds" @result)))))
    
    (run-all-tests #"controller")
In general I use option 2 when I can get away with it, and option 3 where necessary. Option 3 adds enough additional code that I'd probably look into Midje quickly if I found myself writing a more than a few tests that way. However, I generally go out of my way to design pure functions, and I don't find myself needing either of these techniques very often.

 

From http://blog.jayfields.com/2010/09/clojure-mocking.html

Clojure

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • UUID: Coordination-Free Unique Keys
  • 10 Most Popular Frameworks for Building RESTful APIs
  • All the Cloud’s a Stage and All the WebAssembly Modules Merely Actors
  • Test Execution Tutorial: A Comprehensive Guide With Examples and Best Practices

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: