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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Clojure: Destructuring

Trending

  • Metrics at a Glance for Production Clusters
  • Integrating Model Context Protocol (MCP) With Microsoft Copilot Studio AI Agents
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  1. DZone
  2. Coding
  3. Java
  4. Clojure: Mocking

Clojure: Mocking

By 
Jay Fields user avatar
Jay Fields
·
Sep. 02, 10 · Interview
Likes (0)
Comment
Save
Tweet
Share
6.6K 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.

Related

  • Clojure: Destructuring

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!