04-17.eri-test AssertJ中Java集合的常见断言

你好!作为Java集合系列的一部分,我决定写这篇小文章,列出一些来自AssertJ的最常见的断言方法,这些方法可用于测试Java集合。

Commoncollectionassertions

Thissectionpresentsmostcommonassertions,usedwithJavacollections。Examplesareillustratedusingarray-basedlists,thataremostusedJavadatastructures。

Collectioncontainstheelement

基本情况是检查集合中是否包含特定元素。AssertJ使用以下方法对此进行验证contains()/不含()具有重载版本的元素:

  • contains(Ee,intindex)=检查元素是否出现在特定位置
  • contains(E。。。elements)=接受varargs,例如一个或多个元素并检查它们是否存在任何订购

看一下下面的代码片段:

@测试上市虚空containsElementTest(){清单<整数>数字=清单。newArray清单(1,52,12,39,45,98,100,565,6,13);断言(数字)。contains(12);断言(数字)。不含(50);}

Collectioncontainselementsinany订购

Inordertoverify,thatcollectioncontains a group of elements, it is possible to use two scenarios:

  • 使用contains(E。。 elements)方法和提供元素为varargs
  • 使用contains(Iterable i)接受另一个集合并验证所有元素都包含在原始in中的方法any order

这是使用示例containsAll():

@测试
上市 虚空 containsAllElementsNoMatterOrderTest(){清单<整数> 数字 = 清单newArray清单1 52 12 39 45 98 100 565 6 13);清单<整数> 价值观 = 清单newArray清单52 39 12 1 100);断言数字)。containsAll价值观);
}

Collection contains elements in the 具体顺序

Another case is to validate, that the collection contains not only all specified elements, but also keep the specific order。 To do this, it is possible to use containsExactlyElementsOf()方法。 它接受一个I​​terable,并验证实际集合是否包含给定Iterable的所有元素,而在相同的顺序

看下面的例子:

@测试
上市 虚空 containsAllElementsInOrderTest(){清单<整数> 数字 = 清单newArray清单1 52 12 39 45 98 100 565 6 13);清单<整数> 价值观 = 清单.newArray清单数字);断言数字)。containsExactlyElementsOf价值观);
}

Collection contains no duplicates

Not all Java collections allows duplicates: sets, for example, check for inserted elements and do not allow duplicates. Other collections, like lists, do not offer this functionality. In this case, when you need to asserts that the collection does not have duplicate elements, it is advised to use dosNotHaveDuplicates() method:

@测试
上市 虚空 noDuplicatesTest(){清单<整数> 数字 = 清单.newArray清单1 52 12 39 45 98 100 565 6 13);断言数字)。dosNotHaveDuplicates();
}

Collection contains the element 只有一次

最后一种情况的扩展情况是检查元素是否存在only once. Technically, contains() method allows duplicate entities, so to check that element does not repeat, use containsOnlyOnce()断言。

遵守以下代码片段:

@测试
上市 虚空 containsOnlyOnceTest(){清单<整数> 数字 = 清单.newArray清单1 1 52 12 12 45 45);断言数字)。containsOnlyOnce52);
}

Source code

You can find the full source code for this post in this github repository. If you have questions regarding this post, don't hesitate to contact me. 祝你今天愉快!

from: https://dev.to//andreevich/common-assertions-for-java-collections-in-assertj-4h3g

发布了0 篇原创文章 · 获赞 0 · 访问量 124

猜你喜欢

转载自blog.csdn.net/cunbang3337/article/details/105584178
今日推荐