Intro to TDD with Kotlin and JUnit

Introduction to Practice

Welcome to your first lesson in this course dedicated to practicing Test-Driven Development (TDD) using Kotlin and JUnit. Test-Driven Development is an effective approach that emphasizes writing tests before coding. This methodology helps you design your application with testing as a core element, ensuring each component behaves as expected. In this lesson, you'll learn the fundamentals of TDD along with the Red-Green-Refactor cycle, understanding their roles in creating robust and maintainable code.

This course involves hands-on practice, where you'll receive requirements through tests incrementally. Your task is to implement code that makes each test pass, mirroring a real-world TDD environment. Consider this course guide as your pair programmer, providing you with test-driven prompts to enhance your skills as you advance.

Understanding the Red-Green-Refactor Cycle

As a reminder, the Red-Green-Refactor cycle is central to TDD, guiding your development process:

  • Red: Start by writing a failing test to define the next step.
  • Green: Implement just enough code to pass the test, focusing on functionality.
  • Refactor: Optimize the code for clarity and efficiency without changing its behavior.

Requirements for `calculateDiscount` Function

Below, you’ll find the detailed requirements and corresponding test cases for the calculateDiscount function.

Each requirement focuses on a specific behavior the function must fulfill, guiding you through the TDD process step by step.

1. Correct Discount Application

  • Description: The function must correctly apply a percentage-based discount to an original price.
  • Test Case:
    Kotlin
    import kotlin.test.Test
    import kotlin.test.assertEquals
    
    class DiscountCalculatorTest {
    
        @Test
        fun testCalculateDiscountAppliesCorrectDiscount() {
            // Arrange
            val discountCalculator = DiscountCalculator()
            val originalPrice = 100.0
            val discountPercentage = 20.0
            val expectedDiscountedPrice = 80.0
    
            // Act
            val result = discountCalculator.calculateDiscount(originalPrice, discountPercentage)
    
            // Assert
            assertEquals(expectedDiscountedPrice, result, 0.01)
        }
    }
    The test ensures that the function applies the discount correctly and tolerates minor floating-point deviations.
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