Skip to content

Testing Methodology ‐ Test data generators

Devrath edited this page Oct 24, 2023 · 1 revision

github-header-image (1)

Why is it needed

  • When we are testing classes, Sometimes we need to pass a list of data structure that is complex in nature and would end up duplicating even though only a few fields change in each of them.
  • In Such a scenario we can use test data generators.
  • It is the same as a normal class with a function that provides an object.

Code

Product.kt

data class Product(
    val id: Int,
    val name: String,
    val price: Double,
)

Generators.kt

package com.istudio.code.generators

import com.istudio.code.domain.Product

fun productGenerator() : Product {
    return Product(
        id = 1,
        name = "Current product",
        price = 10.0
    )
}

Our test function

@Test
fun `Test products`() {
   // Observe only we modify just one param and not all the params
   val person1 = productGenerator().copy(id = 1)
   val person2 = productGenerator().copy(id = 2)
}