I would like to write unit tests for functions defined as private using defn-. How can I do this?
Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.
So whether you are using JUnit or SuiteRunner, you have the same four basic approaches to testing private methods: Don't test private methods. Give the methods package access. Use a nested test class.
It turns out that you can use the reader macro #' or var to refer to the private function to be tested. If the private function is in namespace a.b and has the name c:
(ns a.b-test (:use [clojure test])) (deftest a-private-function-test (testing "a private function" (let [fun #'a.b/c] (is (not (fun nil))))))
Following the conversation on this topic here: https://groups.google.com/forum/#!msg/clojure/mJqplAdt3TY/GjcWuXQzPKcJ
I would recommend that you don't write private functions with defn-
but instead put your private functions in a separate namespace (and therefore clj
file, e.g. utils.clj
).
Then you:
(:require [yourappname.utils :refer :all])
Then, any user of your API won't see or have access to these helper functions, unless of course they require the utils file, which presumably means they know what they are doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With