Issue
I have this result as list in my service I wrote this unit test
@SpringBootTest(
classes = [CmsApplication::class],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
internal class IngredientsServiceImplTest {
@Autowired
lateinit var restTemplate: TestRestTemplate
@Test
fun getIngredients() {
val result = restTemplate.getForObject("/ingredients", GetIngredientsQuery.Data::class.java);
assertNotNull(result)
assertTrue(result.ingredients!!.isNotEmpty())
assertEquals(result.ingredients!!.size, 512)
val first: GetIngredientsQuery.Ingredient = result.ingredients!![0]
assertEquals(first.displayName,"Salz")
assertEquals(first.image,"/api/consumer/ingredient/salt/image")
assertEquals(first.popular,false)
assertEquals(first.staple,true)
}
}
here the thing is the list is 512 in size I thought I need to assertEqual all items in list as you can see I do that with the first element any suggestions or maybe this test is enough?
this is the method
override suspend fun getIngredients(locale: String?, supportedApiVersion: Int?): GetIngredientsQuery.Data? {
return this.apollo.buildApolloClient().query(GetIngredientsQuery(this.initRequestConfig(locale, supportedApiVersion)))
.execute().data
}
Solution
If the classes has the correct toString()
method defined you simply can do
assertEquals(expected, actual)
and it's not necessary to loop through all the values in the list.
The idea is you create an expected result that should be the same as you expect from your rest (the actual).
It's not necessary all of those assertNotNull()
, assertTrue()
, if you do the assertEquals()
and there is an empty list or null it will crash anyways so you can delete these asserts.
Pd: Why you want to test 512 items? Tests should be fast, so not sure if having 512 items is worth for you to ensure that your code works.
Example
@Test
fun test() {
val actual = restTemplate.getForObject("/ingredients", GetIngredientsQuery.Data::class.java)
val expected = listOf<Ingredients>(....)
assertEquals(expected, actual)
}
Answered By - Skizo-ozᴉʞS
Answer Checked By - Senaida (JavaFixing Volunteer)