Scalatest "At least one"代替 Forall

标签 scala testing scalatest scalacheck

我在 Scala 中编写了这个测试方法来测试 REST 服务。

@Test def whenRequestProductInfo() {
  // When Request Product Info
  forAll { (productId: Int) =>
      val result = mockMvc().perform(get(s"/products/$productId")
        .accept(MediaType.parseMediaType(APPLICATION_JSON_CHARSET_UTF_8)))
        .andExpect(status.isOk)
        .andExpect(content.contentType(APPLICATION_JSON_CHARSET_UTF_8))
        .andReturn;

      val productInfo = mapper.readValue(result.getResponse.getContentAsString, classOf[ProductInfo])

      // At least one is not null
      // assert(productInfo.getInventoryInfo != null)
  }
}

但我想测试至少有一个productInfo.getInventoryInfo不为null,而不是每个productInfo.getInventoryInfo不为null

最佳答案

假设我们有一个产品 ID 列表:

val productIds: List[Int] = ???

我们应该将从 productIdproductInfo 的转换考虑到另一个 val 中。 (我认为这种方法或类似的方法会存在于您其他地方的代码中)。

val inventoryInfo = productIds.map { case productId =>
    val result = mockMvc().perform(get(s"/products/$productId")
        .accept(MediaType.parseMediaType(APPLICATION_JSON_CHARSET_UTF_8)))
        .andExpect(status.isOk)
        .andExpect(content.contentType(APPLICATION_JSON_CHARSET_UTF_8))
        .andReturn

    val productInfo = mapper.readValue(result.getResponse.getContentAsString, classOf[ProductInfo])
    productInfo.getInventoryInfo
 }

现在我们有了一个库存信息列表,无论是什么类型。我们可以使用 atLeast 来检查集合中至少一项库存信息不为 null

atLeast(1, inventoryInfo) should not be null

ScalaTest 似乎没有像 forAll 这样的柯里化(Currying)版本,因此语法有很大不同,如果您需要进行大量计算,则语法不太好。

关于Scalatest "At least one"代替 Forall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29829200/

相关文章:

Scalatest 模拟数据库

scala - 简洁但可扩展的 Scala/sbt 测试以验证 Project Euler 答案

r - 如何计算残差的相关性? Spark-Scala

eclipse - 不使用 Eclipse 运行 Selenium 测试用例/套件

node.js - 是否可以让一个 Discord 机器人向另一机器人发送私信?

android - Android 测试项目中的参数化 JUnit 测试

scala - Scala REPL/SBT Console是否有配置文件?

mongodb - 如何使用 Cashbah MongoDB 连接?

scala - 负数上的 toString 无法在 Scala 工作表中编译

scala - 未找到 Scala 特征中的 @Test 方法