检查 JsonPath 中的空对象

Checking null objects in JsonPath

我正在尝试为 Gatling 模拟验证一些 JsonPath 对象,它对非空对象工作正常,但对 "null" 个对象失败。

实际上字符串 "null" 和对象 null 比较失败了,我该如何处理这种情况?

我们正在检查错误如下,

.check(jsonPath("$.userId").ofType[String].is("null"))

.check(jsonPath("$.userId").ofType[Any].is(null))

但是,出现错误

failed: jsonPath($.userId).find.is(null), but actually found null

运气好

似乎 Gatling 检查系统没有设置好处理 null;假设一切都使用 Option,但这不是它的 JSON 处理方式。

不过,您可以使用更通用的 validate() 方法来解决此问题。首先定义一个简单的验证器:

def notNull[T] = new Validator[T] {
  val name = "notNull"
  def apply(actual : Option[T]) : Validation[Option[T]] = {
    actual match {
      case Some(null) => Failure("but it's so null you guys")
      case _          => Success(actual)
    }
  }
}

然后:

.check(jsonPath("$.userId")).validate(notNull[String])

比我的第一个更好的答案是:

jsonPath("$.userId").ofType[Option[String]].not(None)

毕竟这是Scala;我们不善待这里的 null

不幸的是,这不起作用,因为 Gatling 缺少 OptionJsonFilter。不过不难写:

implicit def optionJsonFilter[T : JsonFilter] : JsonFilter[Option[T]] = {
  new JsonFilter[Option[T]] {
    def filter = {
      case null  => None
      case other => {
        val subfilter : JsonFilter[T] = implicitly
        Some(subfilter.filter(other))
      }
    }
  }
}

(如果是未来并且加特林机已修复此问题,请进行编辑。)

您可以使用原始 Gatlin DSL API 进行 null 检查:

check(jsonPath("$.userId").notNull)

有关详细信息,请参阅 Validating