Continue Developing the calculateDiscount Function

Welcome to your second lesson, which continues to delve into Test Driven Development (TDD) practices using Scala 3, ScalaTest, and Mockito. In this unit, we will extend the functionality of our calculateDiscount function by implementing five new requirements.

Building on the previous unit, this course emphasizes practical experience by sequentially providing requirements through tests. Your mission is to implement code that satisfies each test, mirroring a real-world TDD scenario. Consider this guide your pair programmer, offering test-driven prompts to enhance your expertise incrementally.

Understanding the Red-Green-Refactor Cycle

As a reminder, the Red-Green-Refactor cycle is crucial in TDD, steering your development process:

  • Red: Begin by writing a failing test to define what to do next.
  • Green: Develop just enough code to pass the test, concentrating on meeting the functionality.
  • Refactor: Enhance the code for clarity and efficiency without changing its behavior.
More Requirements for calculateDiscount Function

Below, you'll find additional requirements and tests designed to handle edge cases, such as negative discount percentages and capping maximum discounts.

These enhancements aim to ensure the calculateDiscount function remains robust and reliable under various conditions.

6. Negative Discount Percentage
  • Description: The function should not accept negative discount percentages and must throw an error in such cases.
  • Test Case:
    it("should throw Exception for discounts less than zero percent"):
      // Arrange
      val calculator = DiscountCalculator
      val originalPrice = 100.0
      val discountPercentage = -10.0
    
      // Act & Assert
      the[IllegalArgumentException] thrownBy {
        calculator.calculateDiscount(originalPrice, discountPercentage)
      } should have message "Discount cannot be negative"
    This test ensures that the function throws an exception when a negative discount percentage is provided.
7. Handling Very Small Prices
  • Description: The function should ensure that discounted prices don’t dip below the minimum limit due to very small original prices.
  • Test Case:
    it("handles very small prices correctly"):
      // Arrange
      val calculator = DiscountCalculator
      val originalPrice = 0.001
      val discountPercentage = 1.0
      val expectedDiscountedPrice = 0.01
    
      // Act
      val result = calculator.calculateDiscount(originalPrice, discountPercentage)
    
      // Assert
      result.shouldBe(expectedDiscountedPrice +- 0.001)
    This test checks that the function prevents discounted prices from dropping below a specified minimum when dealing with very small prices.
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