0
0
JUnittesting~10 mins

Test class organization in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test class demonstrates how to organize tests using JUnit 5. It includes setup and teardown methods and two simple test methods verifying basic math operations.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {

    private Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
    }

    @AfterEach
    void tearDown() {
        calculator = null;
    }

    @Test
    void testAddition() {
        int result = calculator.add(2, 3);
        assertEquals(5, result, "2 + 3 should equal 5");
    }

    @Test
    void testSubtraction() {
        int result = calculator.subtract(5, 3);
        assertEquals(2, result, "5 - 3 should equal 2");
    }
}

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    int subtract(int a, int b) {
        return a - b;
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1JUnit starts test run for CalculatorTest classTest runner initialized, no tests executed yet-PASS
2BeforeEach method setUp() is called to initialize Calculator instanceCalculator instance created and ready for test-PASS
3testAddition() method is executedCalculator instance available, inputs 2 and 3 providedassertEquals verifies result is 5PASS
4AfterEach method tearDown() is called to clean up Calculator instanceCalculator instance set to null-PASS
5BeforeEach method setUp() is called again before next testNew Calculator instance created for next test-PASS
6testSubtraction() method is executedCalculator instance available, inputs 5 and 3 providedassertEquals verifies result is 2PASS
7AfterEach method tearDown() is called to clean up Calculator instanceCalculator instance set to null-PASS
8JUnit completes test run for CalculatorTest classAll tests executed successfully-PASS
Failure Scenario
Failing Condition: Calculator's add method returns incorrect result
Execution Trace Quiz - 3 Questions
Test your understanding
What is the purpose of the @BeforeEach method in this test class?
ATo clean up resources after all tests
BTo run the test methods
CTo create a new Calculator instance before each test
DTo assert test results
Key Result
Organizing tests with setup and teardown methods (@BeforeEach and @AfterEach) ensures each test runs independently with a fresh state, preventing interference between tests.