0
0
Kotlinprogramming~30 mins

Test fixtures and lifecycle in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Test fixtures and lifecycle
📖 Scenario: You are writing simple tests for a calculator app. You want to set up a calculator object before each test and clean up after each test.
🎯 Goal: Learn how to use test fixtures and lifecycle methods in Kotlin tests to prepare and clean up test data.
📋 What You'll Learn
Create a Calculator class instance as a test fixture
Use @BeforeEach to initialize the Calculator before each test
Use @AfterEach to reset the Calculator after each test
Write a simple test method that uses the Calculator
💡 Why This Matters
🌍 Real World
Test fixtures and lifecycle methods help prepare and clean up data for automated tests in real apps.
💼 Career
Understanding test lifecycle is essential for writing reliable unit tests in Kotlin development jobs.
Progress0 / 4 steps
1
Create Calculator class and test fixture variable
Create a Kotlin class called Calculator with a method add(a: Int, b: Int): Int that returns the sum of a and b. Then create a test class called CalculatorTest and declare a variable calculator of type Calculator? initialized to null.
Kotlin
Need a hint?

Define the Calculator class with an add method. Declare a nullable Calculator variable in the test class.

2
Initialize Calculator before each test
In the CalculatorTest class, add a method annotated with @BeforeEach called setup that creates a new Calculator instance and assigns it to the calculator variable.
Kotlin
Need a hint?

Use @BeforeEach annotation and assign a new Calculator to calculator inside setup.

3
Reset Calculator after each test
In the CalculatorTest class, add a method annotated with @AfterEach called tearDown that sets the calculator variable to null.
Kotlin
Need a hint?

Use @AfterEach annotation and set calculator to null inside tearDown.

4
Write a test using the fixture
In the CalculatorTest class, add a test method annotated with @Test called testAdd that uses the calculator variable to call add(2, 3) and prints the result.
Kotlin
Need a hint?

Use @Test annotation and print the result of calculator?.add(2, 3).