Testing in Kotlin
# CHAPTER 27
Testing in Kotlin
1. Chapter Introduction
Imagine writing a complex tax calculation function. You test it with a few numbers, and it seems fine. A year later, you add a new feature, accidentally altering the tax logic. Unless you manually re-test every tax scenario, the bug will make it to production. Automated Testing prevents this. In this chapter, we will learn how to write Unit Tests using the JUnit framework to mathematically prove that our Kotlin functions work exactly as intended.2. Learning Objectives
By the end of this chapter, you will be able to:- Understand the purpose of Unit Testing.
- Understand Test-Driven Development (TDD).
-
Use JUnit annotations (
@Test).
-
Write assertions (
assertEquals,assertTrue).
- Structure a test using Arrange-Act-Assert.
3. What is Unit Testing?
A Unit Test is a small script that executes a tiny, isolated portion of your code (a "unit", usually a single function) and verifies that the output matches expectations.If the output matches, the test Passes (Green). If it doesn't match, the test Fails (Red).
4. The Arrange-Act-Assert Pattern
A good test is structured in three phases:- 1. Arrange: Set up the test data (create variables, objects).
- 2. Act: Call the actual function you want to test.
- 3. Assert: Check if the result is exactly what you expected.
5. Writing a Simple Test (JUnit)
First, let's look at the function we want to test. It lives in oursrc/main/kotlin folder.
Now, we create a Test Class in our src/test/kotlin folder. We use the @Test annotation to tell JUnit that this is an executable test.
When you run this test in IntelliJ, you will get a satisfying Green Checkmark! ✅
6. Common Assertions
JUnit provides several helper functions to check results.-
assertEquals(expected, actual): Checks if two values are equal.
-
assertNotEquals(unexpected, actual): Checks if they are different.
-
assertTrue(condition): Checks if a boolean is true.
-
assertFalse(condition): Checks if a boolean is false.
-
assertNull(object): Checks if an object is null.
7. Edge Cases
You shouldn't just test the "happy path" (like5 + 10). You must test Edge Cases! What happens with negative numbers? What happens with zero?
8. Test-Driven Development (TDD)
TDD is a professional workflow where you write the test *before* you write the actual code!- 1. Red: Write a test for a feature that doesn't exist yet. Run it. It fails.
- 2. Green: Write the bare minimum Kotlin code to make the test pass.
- 3. Refactor: Clean up the Kotlin code. The test ensures you didn't break anything!
9. Common Mistakes
-
Testing multiple things in one test: A test should focus on one specific behavior. If a test fails, you should immediately know why based on the test name. Instead of
testCalculator(), writetestAddition()andtestDivisionByZero().
- Not running tests before committing: The purpose of tests is regression safety. Always run the entire test suite before pushing code to GitHub.
10. Best Practices
- Descriptive Test Names: Use long, descriptive names for your test functions. Some Kotlin developers even use backticks to allow spaces in test names:
@Test fun \Adding two negative numbers returns correct negative sum\() { ... }
11. Exercises
*(Theoretical)*-
1.
We have a function
fun isAdult(age: Int): Boolean = age >= 18.
-
2.
Write a JUnit test using
@Test.
-
3.
Call
isAdult(20).
-
4.
Use
assertTrue()to verify the result.
12. MCQs with Answers
What is the primary purpose of automated Unit Testing?
What is the most popular testing framework used in Kotlin/Java?
What annotation must be placed above a function to mark it as an executable test?
What does the "Arrange" step in testing mean?
Which assertion checks if a specific boolean condition evaluates to true?
If val result = 50, what will assertEquals(100, result) do?
What does TDD stand for?
In TDD, when do you write the test?
What is an "Edge Case" in testing?
Why is it important to have an automated test suite?
13. Interview Questions
- Q: Explain the Arrange, Act, Assert pattern in Unit Testing.
- Q: What is TDD, and what are its benefits? (Answer: TDD forces you to think about the requirements and API design before writing the logic. It also guarantees high test coverage from day one).