Enhancing Shopping Cart Functionality with TDD in Kotlin

Additional Features for Shopping Cart

Welcome to the fourth unit of our course, focusing on enhancing your Test Driven Development (TDD) skills with Kotlin and JUnit. We will be expanding our ShoppingCart system by adding additional features.

This hands-on lesson emphasizes receiving requirements through tests, one at a time. Your task is to write tests AND implement the code to pass each test, simulating a real-world TDD environment.

Remember to employ the core concepts of the Red-Green-Refactor cycle while completing these coding exercises. I'm here to assist! Just ask if needed.

New Requirements for ShoppingCart Class

The following requirements introduce additional features for the ShoppingCart class, enabling robust handling of discounts, item management, and overall cart operations.

These enhancements will help solidify your TDD skills while building a more versatile system!

6. Removing a Non-Existent Item

  • Description: Trying to remove an item that is not present in the cart should throw an exception indicating that the item was not found.

  • Details:

    • Implement the removal through a removeItem(id: Int) method.
    • Ensure the method throws an exception with an appropriate message if the item is not found in the cart.
  • Examples: Attempting to remove an item with Id: 999 should throw an exception with the message "Item not found".

class ShoppingCart {
    private val items = mutableMapOf<Int, Int>()

    fun removeItem(id: Int) {
        if (!items.containsKey(id)) {
            throw Exception("Item not found")
        }
        items.remove(id)
    }
}

7. Applying Percentage Discount

  • Description: Applying a percentage discount should adjust the total price of the items in the cart accordingly.

  • Details:

    • Use the applyDiscount(percentage: Double) method to apply a percentage discount to the total.
    • Ensure getTotal() returns the adjusted price after applying the discount.
  • Examples: Applying a 10% discount to a total price of 100 should result in a new total of 90.

class ShoppingCart {
    private var total: Double = 0.0

    fun applyDiscount(percentage: Double) {
        total -= total * (percentage / 100)
    }

    fun getTotal(): Double {
        return total
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal