-
Notifications
You must be signed in to change notification settings - Fork 0
Junit5 β Parameterized Tests
Devrath edited this page Oct 24, 2023
·
1 revision
- 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 presentvalueSource
csvFileSource
csvSource
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 }
}
}
- 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)
}
}
- 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)
}