2012-08-15 84 views
13

如何測試引發預期異常的函數?下面是拋出異常的函數:如何編寫測試來處理預期的異常?

(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))) 

我想設計就像其中一個異常被拋出一把抓住,然後比較下一個測試。以下不工作:

(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"))))) 

我得到這些錯誤:

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.  

很顯然,我失去了一些東西約編寫測試。我無法弄清楚這一點。我的項目是用lein new建立的,我正在用lein測試來運行測試。

謝謝。

+0

可能的重複[我如何期望單元測試失敗?](http://stackoverflow.com/questions/7852092/how-do-i-expect-failure-in-a-unit-test) – 2012-08-15 16:41:52

回答

15

您測試中的最後一個斷言是不正確的;它應該是(is (= excp1 "s-o-m is not a sequence")),因爲map1不是地圖序列。

除此之外,使用(is (thrown? ..))(is (thrown-with-msg? ...))來檢查拋出的異常可能更爲清楚。

+0

+1使用(拋出?...) – Alex 2012-08-15 18:28:51