首页 » 语言&开发 » Java » 断言工具AssetJ示例

断言工具AssetJ示例

 

强大的断言工具AssertJ使用示例。

// 检查:开头结尾和长度
assertThat("Frodo").startsWith("Fro").endsWith("do").hasSize(5);
assertThat("Frodo").doesNotStartWith("fro").doesNotEndWith("don");
// 检查:包含
assertThat("Frodo").contains("rod").doesNotContain("fro").contains("rod", "Fro");
// 检查:被包含
assertThat("Frodo").isSubstringOf("Frodon");
// 检查:仅包含一次
assertThat("Frodo").containsOnlyOnce("do");
// 检查:按顺序检查包含
String bookDescription = "{ 'title':'Games of Thrones', 'author':'George Martin'}";
assertThat(bookDescription).containsSequence("{", "title", "Games of Thrones", "}");
// 检查:忽略大小写;长度检查
assertThat("Frodo").isEqualToIgnoringCase("FROdO").hasSameSizeAs("12345");
assertThat("Frodo".length()).isGreaterThan("Sam".length());
assertThat("C-3PO").hasSameSizeAs("R2-D2").hasSize(5);
// 检查:正则匹配检查
assertThat("Frodo").matches("..o.o").doesNotMatch(".*d");
assertThat("Frodo").containsPattern("Fr.d");
assertThat("Frodo").containsPattern(Pattern.compile("Fr.d"));
// 检查:空串检查
assertThat("").isEmpty();
assertThat("").isNullOrEmpty();
assertThat("not empty").isNotEmpty();
// 检查:数字包含检查
assertThat("3210").containsOnlyDigits();
// 检查:等于;不等于;或者差值范围
assertThat(38).isEqualTo(38).isCloseTo(40, within(10));
assertThat(5.0).isCloseTo(6.0, withinPercentage(20.0));
assertThat(33).isEqualTo(33).isNotEqualTo(34);

// 检查: <= < > >=
assertThat(55).isGreaterThan(44).isGreaterThanOrEqualTo(53);
assertThat(44).isLessThan(55).isLessThanOrEqualTo(45);
assertThat(44).isBetween(33, 55);

// 检查:正数 0 负数
assertThat(0).isZero();
assertThat(-1).isNegative();
assertThat(1).isPositive();

assertThat(0).isNotNegative();
assertThat(0).isNotPositive();
assertThat(1).isNotNegative();
assertThat(-1).isNotPositive();

// 检查:数组 顺序检查
assertThat(new int[] {-1, 2, 3}).contains(-1, 2);
assertThat(new float[] {1.0f, 2.0f, 3.0f}).containsSubsequence(1.0f, 3.0f);
// use SoftAssertions instead of direct assertThat methods
AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions();
softly.assertThat(7).as("Living Guests").isEqualTo(7);
softly.assertThat("dirty").as("Kitchen").isEqualTo("clean");
softly.assertThat("dirty").as("Library").isEqualTo("clean");
softly.assertThat(5).as("Revolver Ammo").isEqualTo(6);
softly.assertThat("pristine").as("Candlestick").isEqualTo("pristine");
softly.assertThat("well kempt").as("Colonel").isEqualTo("well kempt");
softly.assertThat("bad kempt").as("Professor").isEqualTo("well kempt");
// Don't forget to call SoftAssertions global verification
softly.assertAll();

运行结果如下:
org.assertj.core.api.SoftAssertionError: 
The following 4 assertions failed:
1) [Kitchen] expected:<"[clean]"> but was:<"[dirty]">
at SoftAssertJ.test(SoftAssertJ.java:16) expected:<"[clean]"> but was:<"[dirty]">
2) [Library] expected:<"[clean]"> but was:<"[dirty]">
at SoftAssertJ.test(SoftAssertJ.java:17) expected:<"[clean]"> but was:<"[dirty]">
3) [Revolver Ammo] expected:<[6]> but was:<[5]>
at SoftAssertJ.test(SoftAssertJ.java:18) expected:<[6]> but was:<[5]>
4) [Professor] expected:<"[well] kempt"> but was:<"[bad] kempt">
at SoftAssertJ.test(SoftAssertJ.java:21) expected:<"[well] kempt"> but was:<"[bad] kempt">
List<String> list = Lists.newArrayList("a", "b", "c");
List<String> moreList = Lists.newArrayList("d", "a", "b", "c");

// 校验: 数据存在的位置
assertThat(list).contains("a", atIndex(0)).contains("b", atIndex(1)).contains("c", atIndex(2));
// 校验: 存在唯一元素
assertThat(list).containsOnlyOnce("a");
// 校验: 数据子集
assertThat(list).isSubsetOf(moreList);
// 校验: 开头结尾元素
assertThat(list).endsWith("c").startsWith("a");
// 校验: 基于filter过滤校验
assertThat(list).filteredOn(character -> character.contains("a")).containsOnly("a");
Map<String, String> map = Maps.newHashMap();
map.put("Key1", "Value1");
map.put("Key2", "Value2");
map.put("Key3", "Value3");

// 校验:key
assertThat(map).as("map test info").containsOnlyKeys("Key1", "Key2", "Key3");
// 校验:all entry
assertThat(map).containsOnly(entry("Key1", "Value1"), entry("Key2", "Value2"), entry("Key3", "Value3"))
    .contains(entry("Key1", "Value1"));
// 校验:entry
assertThat(map).contains(entry("Key1", "Value1")).containsEntry("Key1", "Value1");
// 校验:不包含
assertThat(map).doesNotContainEntry("1", "2").doesNotContainKey("1").doesNotContainValue("2");
// 校验:size
assertThat(map).isNotEmpty().hasSize(3);
// 类自身属性校验
assertThat(Test.class).isAnnotation();
assertThat(ClassAssertJ.class).isNotAnnotation();
assertThat(ClassAssertJ.class).isNotInterface();
assertThat(ClassAssertJ.class).isNotFinal();
assertThat(ClassAssertJ.class).isNotOfAnyClassIn(Test.class);

// 以下是实例对象的比较,以及实例属性的比较
Person cPerson = new Person(null, 33, "M");
Person aPerson = new Person("a", 33, "M");
Person aPersonClone = new Person("a", 33, "M");
// 每个属性都做比较
assertThat(aPerson).isEqualToComparingFieldByField(aPerson).isEqualToComparingFieldByField(aPersonClone);
// 忽略null值属性,其他每个属性都做比较
assertThat(aPerson).isEqualToIgnoringNullFields(cPerson);
// 忽略部分属性字段,其他字段做比较
assertThat(aPerson).isEqualToIgnoringGivenFields(cPerson, "name", "age");
// 只比较给出的属性字段,属性的属性也支持比较如:a.b
assertThat(aPerson).isEqualToComparingOnlyGivenFields(cPerson, "sex");
Date testDate = df.parse("2002-12-18 0:0:0");
Date dateBefore = new Date(testDate.getTime() - 10);
Date dateAfter = new Date(testDate.getTime() + 10);

// 校验:日期相等、之前、之后,支持字符串参数
assertThat(testDate).isEqualTo("2002-12-18").isAfter(dateBefore).isBefore(dateAfter).isNotEqualTo("2002-12-19")
    .isAfter("2002-12-17").isBefore("2002-12-19");
// 校验:年份
assertThat(testDate).isBeforeYear(2004).isAfterYear(2001);
// 校验:in ; not in
assertThat(testDate).isIn("2002-12-17", "2002-12-18", "2002-12-19").isNotIn("2002-12-17", "2002-12-19");
// 校验:isBetween ; isNotBetween
assertThat(testDate).isBetween("2002-12-17", "2002-12-19").isNotBetween("2002-12-17", "2002-12-18");
// 校验:fastTime 毫秒检查
assertThat(new Date(42)).hasTime(42);
// 校验:过去时间判断
assertThat(new Date(new Date().getTime() - 1)).isInThePast();
// 校验:未来时间判断
assertThat(new Date(new Date().getTime() + 1000000)).isInTheFuture();
// 校验:年月日分别校验
assertThat(testDate).isInSameDayAs("2002-12-18");
assertThat(testDate).isInSameMonthAs("2002-12-22");
assertThat(testDate).isInSameYearAs("2002-11-01");
// java8:异常类型、内容校验
assertThatThrownBy(() -> {
    throw new Exception("boom!");
}).isInstanceOf(Exception.class).hasMessageContaining("boom");

Throwable thrown = catchThrowable(() -> {
    throw new Exception("boom!");
});
assertThat(thrown).isInstanceOf(Exception.class).hasMessageContaining("boom");

// java7
try {
    throw new IndexOutOfBoundsException("Index: 9, Size: 9");
} catch (IndexOutOfBoundsException e) {
    assertThat(e).hasMessage("Index: 9, Size: 9");
}


原文链接:断言工具AssetJ示例,转载请注明来源!

1