1

I have implemented retry policy for update function (talking to database) - if update throws exception I retry it up to 10 times. I am mocking the update function with midje. I want to simulate that first time it fails and second time it succeeds. I tried this :

(fact "update is retried when failed"
  (ud/ensure-data {:username ..username.. :data :h}) => ..result..
  (provided
    (ud/get-raw-user-data ..username..) => example-user-data-raw
    (ud/update-user-data {:username ..username..
                          :version 1
                          :userdata {:data {:h {}}}}) =throws=> (Exception.)
    (ud/update-user-data {:username ..username..
                          :version 1
                          :userdata {:data {:h {}}}}) => ..result..))

but this doesn't seem to work...... Response is :

These calls were not made the right number of times:
(ud/update-user-data {:username ..username.., :version 1, :userdata {:homebases {:h {:sensors []}}}}) [expected at least once, actually never called]

I also found streams (https://github.com/marick/Midje/wiki/Variant-prerequisite-arrows) but I don't know how to combine Exceptions with success calls with streams.

bsvingen
  • 2,699
  • 14
  • 18
Viktor K.
  • 2,670
  • 2
  • 19
  • 30

1 Answers1

0

I haven't got a clear understanding of how to use Midje streams either. So my personal solution is, in a word, not to use provided or 'streams', but use with-redefs and 'stubs'.

(defn fn0 [] -1) ;; function we want to mock

;; fn1 retries fn0 if there is an exception
(defn fn1 [] (try 
               (fn0)
               (catch Exception e 
                      (do
                         (prn "Exception Caught, try again...")
                         (fn0)))))

(def call-count (atom -1))     ;; counts how many times fn0 is called

;; stub fn0 by returning different result
(defn make-stub [& result-seqs]
  (fn [& _]
    (swap! call-count inc)
    (let [result (nth result-seqs @call-count)]
      (if (instance? Throwable result)
        (throw result)
        result))))

(fact "fn1 ignores first exception and returns second call to fn0"
  (with-redefs [fn0 (make-stub (Exception. "stubbed error") 100)]
    (fn1) => 100))
Alfred Xiao
  • 1,758
  • 15
  • 16