Scalatest "At least one" 而不是 Forall

Scalatest "At least one" instead for Forall

我在 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 不为空 而不是 每个 productInfo.getInventoryInfo 不为空.

假设我们有一个产品 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 这样的任何柯里化版本,因此语法有很大不同,如果您需要进行大量计算,则语法不太好。

forAll 可以通过配置所需的成功评估次数和允许的失败评估次数。这应该完成你正在寻找的东西。 Documentation here在页尾。

示例:

forAll (minSuccessful(1)) { (productId: Int) =>  ...