【问题标题】:Checking array item convert from jsonPath to JUnit hamcrest matcher检查数组项从 jsonPath 转换为 JUnit hamcrest 匹配器
【发布时间】:2020-07-01 15:08:37
【问题描述】:

几乎没有尝试检查 json 是否有包含两个项目的数组:

{
  "sections" : [
    {
      "name" : "A",
      "description" : "aaa"
    },
    {
      "name" : "B",
      "description" : "bbb"
    }
  ]
}

但只是附带

.andExpect(jsonPath("$.sections[?(@.name=='A' && @.description=='aaa')]", hasSize(1)))

有什么方法可以使用 hasItem/hasProperty/containInAnyOrder 将其转换为 Harmcrest 匹配器?

【问题讨论】:

    标签: java junit jsonpath hamcrest


    【解决方案1】:

    我认为将 Json 数组反序列化为 Section 对象列表将很容易使用 Hamcrest 匹配器。您必须重写 equals() 方法以检查 Section 对象是否在创建的 Section 列表中可用。

    Section.java

    public class Section {
        private String name;
        private String description;
    
        public Section(String name, String description) {
            this.name = name;
            this.description = description;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
    
            if (obj.getClass() != this.getClass()) {
                return false;
            }
    
            final Section other = (Section) obj;
            if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
                return false;
            }
    
            if (!this.description.equals(other.description)) {
                return false;
            }
    
            return true;
        }
    }
    

    然后使用您喜欢的任何 Hamcrest Matcher。

    RestAssured.baseURI="https://run.mocky.io/v3/bc929050-35ba-42a1-86b1-58f3fd1ead83";
    
    List<Section> sections =  RestAssured.given()
            .when()
            .get()
            .then()
            .extract().jsonPath().getList("sections", Section.class);
    
    Section sectionA = new Section("A", "aaa");
    Section sectionB = new Section("B", "bbb");
    
    List<Section> sectionList = new ArrayList<>();
    sectionList.add(sectionA);
    sectionList.add(sectionB);
    
    assertThat(sections, hasItem(sectionA)); // pass
    assertThat(sections, hasSize(2)); // pass
    assertThat(sections, hasItem(hasProperty("name", equalTo("B")))); // pass
    assertThat(sections, equalTo(sectionList)); // pass
    assertThat(sections, containsInAnyOrder(sectionList.toArray())); // pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2018-10-07
      相关资源
      最近更新 更多