errob37
errob37

Reputation: 13

Clojure - how to instrument another protocol in implementation

I'm new in Clojure and after searching for it, I turning my problem to SO community.

I'm testing a protocol implementation (deftype) who has a reference to another protocol, so constructor is like this :

(deftype FooImpl [^Protocol2 protocol-2]
    (function bar [_] ... (.bar2 protocol-2))
) 

The ... are somes conditions too meet to call the .bar2 function.

The thing that I'm not able to do, is to instrument (conjure.core/instrumenting) the call the .bar2 to validate passed parameter (verify-called-once-with-args).

So problem is this:

(instrumenting [ns/function ;;In normal case with `defn`
                ????] ;; what to write for .bar2
   ....)

Thanks!

Upvotes: 1

Views: 132

Answers (1)

For normal usage or for testing/mocking you can use reify to implement the protocol:

(instrumenting [ns/function]
  (ns/function (reify Protocol2
                 (bar2 [_]
                   ; Your mock return value goes here
                   42))))

You can also roll your own checking by using atom:

(instrumenting [ns/function]
  (let [my-calls (atom 0)]
    (ns/function (reify Protocol2
                   (bar2 [_]
                     ; Increment the number of calls
                     (swap! my-calls inc)
                     ; Your mock return value goes here
                     42)))
    (is (= @my-calls 1))))

The above assumes you're using clojure.test, but any of the clojure unit testing libs can verify your atom's value.

Upvotes: 1

Related Questions