2017-04-12 30 views
2

我正在測試函數的返回值。哪兩個是首選的方式?ExUnit沒有斷言/反駁,完全依賴於模式匹配?

test "extra verbose, using assert" do 
    {:error, reason} = MyModule.my_fun 
    assert reason == :nope 
end 

test "using pattern matching only" do 
    {:error, :nope} = MyModule.my_fun 
end 

我喜歡的第一個原因,我現在不,測試需要一個assert語句和錯誤消息時運行測試是更具描述。 Otoh,MatchError與行號也應該足夠。

回答

6

您可以使用assert=兩全的assert和更具描述性的錯誤消息,並且只用一行代碼:

assert {:error, :nope} = MyModule.my_fun 

不像==,您可以在LHS用途的任何圖案,儘管在這種情況下,=可以替換爲==,因爲LHS既是有效的模式也是有效的值。

如果失敗,您將收到一條錯誤消息,該消息比只使用assert(例如assert)進行模式匹配要好。

1) test the truth (MTest) 
    test/m_test.exs:10 
    match (=) failed 
    code: {:error, :nope} = MyModule.my_fun() 
    right: {:error, :nop} 
    stacktrace: 
     test/m_test.exs:11: (test) 
+0

對我來說,主要的缺點使用斷言在比賽中,你不會得到左VS測試正確的比較結果 – Stuart

+0

是'斷言{:錯誤:沒有耶} = MyModule.my_fun'真正測試什麼?如果模式匹配,它基本上會聲明元組{:error,:nope}是真的,不是?如果模式不匹配,那麼仍然存在'MatchError'。 – carp

+1

@carp nope,不會有任何'MatchError'。 'assert'特別處理'='。我剛纔給答案添加了一個示例測試失敗輸出。 – Dogbert