EUnit 基本使用

EUnit是一個對Erlang輕量級的單元測試框架.

一、如何在Erlang中應用EUnit?

1、引入EUnit的頭文件,分3種方法(任選其一).
(1). 在要用單元測試的每一個module中引入
-include_lib("eunit/include/eunit.hrl").
(2). 啓動Eralng時指定Eunit路徑
erlc -pa "path/to/eunit/ebin" $(ERL_COMPILE_FLAGS) -o$(EBIN) $<
(3). 在$HOME/.erlang中加入 code:add_path("/path/to/eunit/ebin").
2、寫一個簡單的測試方法.
新建一個module,名字定爲eunit_start.寫一個方法reverse_test()->lists:reverse([1,2,3]).此時編譯執行eunit_start:test().相應的測試結果就出來了.(注:此module不用export任何方法,test方法爲EUnit內部機制實現的).test方法會調用以_test結尾的方法.
其實test方法會調用_test和_test_結尾的方法.兩者不同點在於_test_結尾的方法會把測試方法放入一個List中依次執行.

二、應用EUnit macros進行測試

EUnit的頭文件(eunit.hrl)中定義了一系列的macros,通過這些macros可以讓我們的單元測試更加簡潔易讀.

基本的macros(Basic macros)

_test(Expr)正如macros定義的一樣 -define(_test(Expr), {?LINE, fun () -> (Expr) end}).

斷言的macros(Assert macros)

assert(BoolExpr) 用法:?assert(f(X, Y) =:= [])
assertNot(BoolExpr)
assertMatch(GuardedPattern, Expr)
用法: ?assertMatch({found, {fred, _}}, lookup(bloggs, Table))
?assertMatch([X|_] when X > 0, binary_to_list(B))
assertEqual(Expect, Expr)
用法: ?assertEqual("b" ++ "a", lists:reverse("ab"))
?assertEqual(foo(X), bar(Y))
assertException(ClassPattern, TermPattern, Expr)
assertError(TermPattern, Expr)
assertExit(TermPattern, Expr)
assertThrow(TermPattern, Expr)
用法: ?assertError(badarith, X/0)
?assertExit(normal, exit(normal))
?assertException(throw, {not_found,_}, throw({not_found,42}))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章