java - 使用 jsonPath 测试值列表中包含的重复值(Hamcrest)

标签 java spring jsonpath hamcrest mockmvc

我有以下 json 结构:

{
  content: [
    {
      status: 100,
    },
    {
      status: 100,
    },
    {
      status: 200,
    },
    {
      status: 300
    }
  ]
}

我在 Spring 中使用以下代码来测试 json 中的任何状态值是否符合状态数组指定的接受值:

jsonPath("$.content[*].status", Matchers.containsInAnyOrder(100, 200, 300));

它失败,因为检查的可迭代与指定项目的数量相同的长度。如果我指定这样的数组 Matchers.containsInAnyOrder(100, 100, 200, 300),那么它会成功。

我检查了匹配器的实现,看起来每次成功的匹配,匹配的值都会从指定的项目中删除。

是否有任何 Hamcrest 匹配器不会删除匹配的项目?

最佳答案

Matchers.containsInAnyOrder

Creates an order agnostic matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to one item anywhere in the specified items.

但是您真正想做的是检查每个项目是否在范围内 一组有效的值,可以写成:

Matchers.everyItem(Matchers.isOneOf(100,200,300))

关于java - 使用 jsonPath 测试值列表中包含的重复值(Hamcrest),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45504741/

相关文章:

带有 Newtonsoft.JSON 的 JsonPath

java - 此 java 对象是否符合 List 中的垃圾回收条件

java - 编写可测试的代码 - Junit Test

java - 从 REST 服务将 .zip 文件作为二进制 InputStream 上传

java - 如何在 int 数组中查找元素的索引?

java - 形成丢失的波兰字符

java - 嵌套对象列表的 Spring 配置属性元数据 json

Spring MVC : Optional vs Exceptions in Service Layer

amazon-redshift - 使用 JSONPath 进行 Redshift COPY 缺失的数组/字段

java - 将 Gson 与路径一起使用