我在 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] = ???
我们应该将从 productId
到 productInfo
的转换考虑到另一个 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/