Skip to content

Junit5 ‐ Parameterized Tests

Devrath edited this page Oct 24, 2023 · 1 revision

github-header-image

About The test

  • We can use this type of test to run multiple tests from a single test case with different inputs as params that change instead of writing a separate new test for each param.
  • Three types of parameterized test are present
    • valueSource
    • csvFileSource
    • csvSource

Code

Class in test

class ShoppingCart {

    private val items = mutableListOf<Product>()

    fun addProduct(product: Product, quantity: Int) {
        if(quantity < 0) {
            throw IllegalArgumentException("Quantity can't be negative")
        }
        repeat(quantity) {
            items.add(product)
        }
    }

    fun getTotalCost(): Double {
        return items.sumOf { it.price }
    }
}

Our test case -----> ValueSource

  • The below test will run twice and each time a new value is passed
@ParameterizedTest
    @ValueSource(
        ints = [2,2]
    )
    fun `Add multiple products, total price sum is correct with parameterized test way`(
        quantityParam : Int
    ){
        val productOne = Product(id = 1, name = "Product-1", price = 1.0)
        cart.addProduct(productOne,quantityParam)
        assertThat(cart.getTotalCost()).isEqualTo(2.0)
    }
}

Our test case -----> csvSource

  • Here we can pass kind of collection of inputs as parameters
  • Here three tests are conducted and all will be passed
    @ParameterizedTest
    @CsvSource(
        "2,2.0",
        "3,3,0",
        "4,4,0"
    )
    fun `Add multiple products, total price sum is correct with parameterised test way`(
        inputParam : Int, expectedParam : Double
    ){
        val productOne = Product(id = 1, name = "Product-1", price = 1.0)
        cart.addProduct(productOne,inputParam)
        assertThat(cart.getTotalCost()).isEqualTo(expectedParam)
    }