首页 > 解决方案 > 春季测试 Kotlin Hamescreat 有匹配器

问题描述

java中的jsonPath断言:

mockMvc.perform(post("/books")
                .content(bookInJson)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$.timestamp", is(notNullValue())))
                .andExpect(jsonPath("$.status", is(400)))
                .andExpect(jsonPath("$.errors").isArray())
                .andExpect(jsonPath("$.errors", hasSize(3)))
                .andExpect(jsonPath("$.errors", hasItem("Author is not allowed.")))

无法在 kotlin 等效项中编译:

mockMvc!!.perform(get("/api/customer/{id}", customer.id))
      .andExpect(status().isOk)
      .andExpect(jsonPath("$.name", equalTo(customer.name)))
      .andExpect(jsonPath("$.idNumber", equalTo(customer.idNumber)))
      .andExpect(jsonPath("$.address", hasSize(0)))
      .andExpect(jsonPath("$.contact", hasSize(0)))
      .andExpect(jsonPath("$.address", hasItem("item")))

hasSize 断言抛出错误:Kotlin: Not enough information to infer type variable T

如何使用 kotlin 在 jsonPath 中执行 hasSize 断言?

标签: kotlinspring-test

解决方案


正如@F43nd1r 所说,指定类型有效。

代码:

mockMvc!!.perform(get("/api/customer/{id}", customer.id))
      .andExpect(status().isOk)
      .andExpect(jsonPath("$.name", equalTo(customer.name)))
      .andExpect(jsonPath("$.idNumber", equalTo(customer.idNumber)))
      .andExpect(jsonPath("$.address", hasSize<String>(0)))
      .andExpect(jsonPath("$.contact", hasSize<String>(0)))
      .andExpect(jsonPath("$.address", hasItem("item")))

推荐阅读