Search code examples
clojure

How do you mock file reading in Clojure


I have the following code that loads edn data from my resources folder:

(defn load-data
  []
  (->> (io/resource "news.edn")
       slurp
       edn/read-string))

I'd like to test this by mocking out the file reading part, so far I have this:

(deftest loading-data
  (is (= (edn/read-string (prn-str {:articles [{:title "ASAP Rocky released" :url "http://foo.com"}]})) (load-data))))

But I know this very flaky test because if the edn file name changes or it's contents or updated, the test will fail. Any ideas?


Solution

  • You can mock out a call to function with with-redefs, that "Temporarily redefines Vars while executing the body". E.g.,

    (deftest load-data-test
      (with-redefs [slurp (constantly "{:a \"b\"}")]
        (is (= (load-data) {:a "b"}))))
    

    This way the slurp in load-data in the scope of with-redefs returns "{:a \"b\"}".