JUnit基礎用法

2021-08-13 08:48:59 字數 2963 閱讀 1760

最近同時在了解kotlin,不管是否會使用到,抱著了解終究是多乙個選擇的心態先學習下。因此本文測試junit的測試類均使用kotlin編寫。

可通過test註解來註解需要測試的方法;當執行時junit將會將所有被test所註解的方法均進行測試;

class ktltesttest 

@test

fun test2()

}

suite為測試套件,也即可以一次性執行多點個需要測試的類;

可以在入口類中通過@runwith指定suite為runner,然後再通過suiteclasses指定該suite中需要測試的類;

示例如下:

@runwith(suite::class)

@suiteclasses(value = *arrayof(ktltesttest::class, testtest::class))

class ktltestsuite

直接執行即可看到結果。

用於對方法進行註解,說明該方法在測試時需要被執行;

test註解主要包含有expected屬性,可指定所希望丟擲的異常型別;也即如果丟擲了指定的異常,則該測試被認為成功,否則為失敗。示例如下:

class ktltesttest 

@test(expected = exception::class)

fun test2()

}

測試套件,包含有一系列的需要測試的類;通過runwith指定suite進行測試時需要使用suiiteclasses指定需要測試的類;

包含常用斷言方法: asserttrue/assertfalse/fail/assertequals/assertnotequals/assertarrayequals/assertnotnull/assertnull/failnotnull/assertsame/assertnotsame/failsame/failnotsame/assertthat

其中以較難理解的assertthat為例,講解其具體用法。

assertthat一般用於根據傳入的值判斷其是否滿足一定規則;

如下列,判斷是否是email:

@test

fun testassertthat()

override fun matches(item: any?): boolean

return regex(patternstr).matches(item.tostring())

}override fun _dont_implement_matcher___instead_extend_basematcher_()

override fun describeto(description: description?)

})}

assertthat一般與corematchers一同使用。

corematchers中提供的方法分成兩類:一是以非matcher物件做引數的,一種是以matcher做引數的;後者為一些針對多個matcher的一些邏輯組合,如同時滿足多個matcher或者滿足多個matcher中的乙個等;

非matcher做引數的方法清單如下: 

方法解釋

用法is

根據傳入引數不同決定作用,如傳入class時表示判斷是否是該class的例項;傳入物件時表示判斷物件是否相等等; 相當於isa/any/instanceof/equalto等方法的乙個功能彙總

not與is相反

isa判斷是否是某個類的例項

hasitem

序列物件中是否包含有某個物件

assertthat(arrays.aslist(「foo」, 「bar」), hasitem(「bar」))

hasitems

序列物件中是否包含多個物件

equalto

與is傳入物件時一致,判斷兩個物件在邏輯上是否一致

any與isa一致

instanceof

與isa/any一致

nullvalue

是否為空

notnullvalue

是否不為空

sameinstance/theinstance

是否同乙個類的例項

containsstring

是否包含字串

startswith

是否以某字串開頭

endswith

是否以某串結尾

matcher做引數的方法清單如下: 

方法解釋

用法allof

滿足所有的matcher

assertthat(「myvalue」, allof(startswith(「my」), containsstring(「val」)))

anyof

滿足某乙個matcher即可

assertthat(「myvalue」, anyof(startswith(「foo」), containsstring(「val」)))

both

同時滿足兩個以上的matcher,它返回的是乙個combinablematcher的物件,可以再使用and等方法與其它的matcher進行聯合判斷

assertthat(「fab」, both(containsstring(「a」)).and(containsstring(「b」)))

either

滿足某乙個即可,與both原理類似

assertthat(「fan」, either(containsstring(「a」)).and(containsstring(「b」)))

everyitem

每乙個元素均滿足某一matcher

assertthat(arrays.aslist(「bar」, 「baz」), everyitem(startswith(「ba」)))

上面提到的combinablematcher,主要提供and/or/either/both等方法來進行聯合判斷。

junit基本用法

很久之前接觸了一點junit,但一直沒用過,最近 量大了,於是回想起junit的好處。junit共就6種注釋,其中用得最多的就是 test注釋 接下來創乙個類 package yc import org.junit.test public class math public int jian int...

JUnit單元測試(二) JUnit基礎

junit單元測試 二 junit基礎 1 基礎介紹 1.junit是一種測試 的框架,測試的目的是 保證 沒錯,而不是保證 正確。2.測試類一般不要和目標類放在一起,但編譯成的class檔案是放在一起的,這樣可以保證產品 與測試 分離,互不影響。3.單元測試主要是來測試程式的結果和自己期望的值是否...

JUnit中assert斷言的用法

它的作用是比較實際的值和使用者預期的值是否一樣 asserttrue與assertfalse可以判斷某個條件是真還是假,如果和預期的值相同則測試成功,否則將失敗 assertnull與assertnotnull可以驗證所測試的物件是否為空或不為空,如果和預期的相同則測試成功,否則測試失敗 asser...