簡(jiǎn)單了解Java斷言利器AssertJ原理及用法
AssertJ是我目前見過的最強(qiáng)大的斷言api,沒有之一。
官網(wǎng)傳送門
為什么使用assertJ?
1、流式斷言,代碼即用例,直觀易懂。
舉個(gè)例子:
傳統(tǒng)的junit或者testng,判斷一個(gè)字符串包不包括a跟b兩個(gè)字符。要這么寫
assertTrue(stringbuffer.contains('a') && stringbuffer.contains('b'))
而如果你用的assertJ
assertThat(stringbuffer).contains('a').contains('b').as('判斷字符串是否包括a|b')
相比之下,顯然后者更加容易理解。而且as的注釋更是讓斷言清晰
2、方便定制的斷言器
試想一下。當(dāng)你在做接口測(cè)試的時(shí)候,還在到處寫著
JSONPath.eval(JSONObject.parse(String),'$yourpath').tostring.equals(expectString)
你的接口自動(dòng)化里邊。到處都是這些看都不想看的json解析,判斷。然而,當(dāng)你有了assertJ,你可以自定義你的斷言,盡可能的簡(jiǎn)化你的測(cè)試代碼,可讀性將能幾何倍數(shù)提升。下邊是我自己寫的一個(gè)針對(duì)json的自定義斷言器:
import java.math.BigDecimal;import org.assertj.core.api.AbstractAssert;import org.assertj.core.api.AbstractBigDecimalAssert;import org.assertj.core.api.AbstractBooleanAssert;import org.assertj.core.api.AbstractCharSequenceAssert;import org.assertj.core.api.AbstractIntegerAssert;import org.assertj.core.api.Assertions;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.JSONPath;/** * assertJ json數(shù)據(jù)判斷增強(qiáng) eg:不提供提取數(shù)組的方法,在斷言中作用比較小 * * @author jacksoncina2008 * */public class AssertJSON extends AbstractAssert<AssertJSON, String> { protected AssertJSON(String actual) { super(actual, AssertJSON.class); // TODO Auto-generated constructor stub } public static AssertJSON assertThat(String json) { return new AssertJSON(json); } /** * 提取字符串節(jié)點(diǎn) */ public AbstractCharSequenceAssert<?, String> jsonPathAsString(String path) { return Assertions.assertThat((String) JSONPath.eval(getJSON(actual), path)); } /** * 提取boolean節(jié)點(diǎn) */ public AbstractBooleanAssert<?> jsonPathAsBoolean(String path) { return Assertions.assertThat((boolean) JSONPath.eval(getJSON(actual), path)); } /** * 提取數(shù)字節(jié)點(diǎn) * */ public AbstractIntegerAssert<?> jsonPathAsInteger(String path) { return Assertions.assertThat((Integer) JSONPath.eval(getJSON(actual), path)); } /** * 提取小數(shù) * */ public AbstractBigDecimalAssert<?> jsonPathAsBigDecimal(String path) { return Assertions.assertThat((BigDecimal) JSONPath.eval(getJSON(actual), path)); } private JSONObject getJSON(String json) { JSONObject j = new JSONObject(); j = JSONObject.parseObject(json); return j; }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用單元測(cè)試對(duì)PHP代碼進(jìn)行檢查2. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML3. python excel和yaml文件的讀取封裝4. moment轉(zhuǎn)化時(shí)間戳出現(xiàn)Invalid Date的問題及解決5. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析6. python3實(shí)現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)7. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊8. python 實(shí)現(xiàn)圍棋游戲(純tkinter gui)9. python 基于Appium控制多設(shè)備并行執(zhí)行10. Python加載數(shù)據(jù)的5種不同方式(收藏)
