2012-08-15 17 views
13

Come posso verificare una funzione che genera un'eccezione prevista? Ecco la funzione che genera l'eccezione:Come posso scrivere un test per gestire un'eccezione prevista?

(defn seq-of-maps? 
    "Tests for a sequence of maps, and throws a custom exception if not." 
    [s-o-m] 
    (if-not (seq? s-o-m) 
    (throw (IllegalArgumentException. "s-o-m is not a sequence")) 
    (if-not (map? (first s-o-m)) 
     (throw (IllegalArgumentException. "s-o-m is not a sequence of maps.")) 
     true))) 

voglio progettare un test come il seguente in cui viene generata un'eccezione e catturato e poi confrontato. Quanto segue non funziona:

(deftest test-seq-of-maps 
    (let [map1 {:key1 "val1"} 
     empv [] 
     s-o-m (list {:key1 "val1"}{:key2 "val2"}) 
     excp1 (try 
       (seq-of-maps? map1) 
       (catch Exception e (.getMessage e)))] 
    (is (seq-of-maps? s-o-m)) 
    (is (not (= excp1 "s-o-m is not a sequence"))))) 

sto ottenendo questi errori:

Testing util.test.core 

FAIL in (test-seq-of-maps) (core.clj:27) 
expected: (not (= excp1 "s-o-m is not a sequence")) 
    actual: (not (not true)) 

Ran 2 tests containing 6 assertions. 
1 failures, 0 errors.  

Ovviamente, mi manca qualcosa sulla scrittura di test. Sto avendo problemi a capirlo. Il mio progetto è stato impostato con lein nuovo e sto eseguendo i test con lein test.

Grazie.

+0

possibile duplicato di [Come prevedere un errore in un test unitario?] (Http://stackoverflow.com/questions/7852092/how-do-i-expect-failure-in-a-unit-test) –

risposta

15

L'ultima affermazione nel test è errata; dovrebbe essere (is (= excp1 "s-o-m is not a sequence")) poiché map1 non è un seq di mappe.

A parte questo, è probabilmente più chiaro utilizzare (is (thrown? ..)) o (is (thrown-with-msg? ...)) per verificare le eccezioni generate.

+0

+1 all'utilizzo (lanciato? ...) – Alex

Problemi correlati