Reputation: 658
I wrote this test method in Scala to test a REST service.
@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)
}
}
But I want to test that at least one productInfo.getInventoryInfo is not null instead of every productInfo.getInventoryInfo is not null.
Upvotes: 2
Views: 827
Reputation: 438
forAll can be passed configuration for the number of successful evaluations needed and number of failed evaluations allowed. This should accomplish what you are looking for. Documentation here at the end of the page.
Example:
forAll (minSuccessful(1)) { (productId: Int) => ...
Upvotes: 2
Reputation: 55569
Assuming we have a list of product ids:
val productIds: List[Int] = ???
We ought to factor the conversion from productId
to productInfo
into another val
. (I would think this method or something similar would exist in your code elsewhere).
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
}
Now we have a list of inventory info, whatever type that is. We can use atLeast
to check that at least one inventory info from the collection is not null
.
atLeast(1, inventoryInfo) should not be null
It doesn't seem like ScalaTest has any curried version of this like with forAll
, so the syntax is much different and not quite as nice if you need to do a bunch of computations.
Upvotes: 2