Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write unit tests for private clojure functions?

Tags:

I would like to write unit tests for functions defined as private using defn-. How can I do this?

like image 712
yakshaver Avatar asked May 26 '16 21:05

yakshaver


People also ask

Can we write unit tests for private methods?

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.

Can we test private methods in unit testing JUnit?

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.


2 Answers

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)))))) 
like image 121
yakshaver Avatar answered Oct 01 '22 04:10

yakshaver


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:

  1. Require this file where you need the private functions, e.g. in your API definition with something like (:require [yourappname.utils :refer :all])
  2. Require this file in your test namespace to test the functions.

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.

like image 27
Eric Clack Avatar answered Oct 01 '22 04:10

Eric Clack