2

我在 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 is not null

4

2 回答 2

2

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

val productIds: List[Int] = ???

我们应该考虑从productIdtoproductInfo到 another的转换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 似乎没有任何类似 with 的 curried 版本forAll,因此语法有很大不同,如果您需要进行大量计算,也不会那么好。

于 2015-04-23T16:44:44.850 回答
2

forAll 可以通过配置所需的成功评估次数和允许的失败评估次数。这应该完成您正在寻找的内容。文档位于页面末尾。

例子:

forAll (minSuccessful(1)) { (productId: Int) =>  ...
于 2015-04-23T17:29:41.320 回答