国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

簡單了解Java斷言利器AssertJ原理及用法

瀏覽:31日期:2022-08-21 13:55:00

AssertJ是我目前見過的最強大的斷言api,沒有之一。

官網傳送門

為什么使用assertJ?

1、流式斷言,代碼即用例,直觀易懂。

舉個例子:

傳統的junit或者testng,判斷一個字符串包不包括a跟b兩個字符。要這么寫

assertTrue(stringbuffer.contains('a') && stringbuffer.contains('b'))

而如果你用的assertJ

assertThat(stringbuffer).contains('a').contains('b').as('判斷字符串是否包括a|b')

相比之下,顯然后者更加容易理解。而且as的注釋更是讓斷言清晰

2、方便定制的斷言器

試想一下。當你在做接口測試的時候,還在到處寫著

JSONPath.eval(JSONObject.parse(String),'$yourpath').tostring.equals(expectString)

你的接口自動化里邊。到處都是這些看都不想看的json解析,判斷。然而,當你有了assertJ,你可以自定義你的斷言,盡可能的簡化你的測試代碼,可讀性將能幾何倍數提升。下邊是我自己寫的一個針對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數據判斷增強 eg:不提供提取數組的方法,在斷言中作用比較小 * * @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); } /** * 提取字符串節點 */ public AbstractCharSequenceAssert<?, String> jsonPathAsString(String path) { return Assertions.assertThat((String) JSONPath.eval(getJSON(actual), path)); } /** * 提取boolean節點 */ public AbstractBooleanAssert<?> jsonPathAsBoolean(String path) { return Assertions.assertThat((boolean) JSONPath.eval(getJSON(actual), path)); } /** * 提取數字節點 * */ public AbstractIntegerAssert<?> jsonPathAsInteger(String path) { return Assertions.assertThat((Integer) JSONPath.eval(getJSON(actual), path)); } /** * 提取小數 * */ 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; }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 司法| 康保县| 金坛市| 贵德县| 和硕县| 井研县| 霍州市| 贺州市| 桃江县| 宁陵县| 原平市| 河津市| 晋中市| 玉林市| 新野县| 互助| 南召县| 沛县| 阳谷县| 石景山区| 田林县| 石林| 光泽县| 宜章县| 临泉县| 中阳县| 石林| 紫金县| 拜泉县| 武乡县| 德阳市| 高青县| 商丘市| 大余县| 高邮市| 且末县| 德庆县| 察雅县| 雷州市| 五大连池市| 兴安盟|