Search code examples
clojuretracemidje

Midje print stacktrace when test fails


I am learning Clojure, and trying to use TDD to do so *.

I use midje as a testing library. Love it so far, the expected versus actual results display is very helpfull.

But is there was a way to use clojure.tools.trace or something similar to print the trace of the first test that fails ?

*: Specifically, I remember seeing a talk by Robert C. Martin about the transformation priority premise, and I'm implementing a factorial function this way. There isn't yet much code to show though.


Solution

  • One possibility would be writing your own emitter but that might be overkill for your specific goal.

    Alternatively, you can monkey-patch the function responsible for formatting the expected values:

    (require '[midje.util.exceptions :as e]
             '[midje.emission.plugins.util :as u])
    
    (defn- format-captured-throwable
      [ex]
      (if (e/captured-throwable? ex)
        ;; ... adjust this to your needs ...
        (pr-str 'this-is-your-exception (e/throwable ex))))
    
    (alter-var-root
      #'u/attractively-stringified-value
      (fn [f]
        #(or (format-captured-throwable %) (f %))))
    

    format-captured-throwable has to produce a string, though, meaning that directly printing the stacktrace will let it end up nowhere near midje's test report.

    user=> (fact (throw (Exception. "khaaaaaaaan.")) => :not-khan)
    
    FAIL at (form-init4689442922606051135.clj:1)
        Expected: :not-khan
          Actual: this-is-your-exception #<Exception java.lang.Exception: khaaaaaaaan.>