0
0
JUnittesting~5 mins

Test independence in JUnit

Choose your learning style9 modes available
Introduction

Test independence means each test runs alone without relying on others. This helps find problems clearly and keeps tests simple.

When writing multiple tests for different features of a program.
When you want to run tests in any order without failures.
When fixing a bug and checking only the related test.
When sharing tests with teammates to avoid confusion.
When running tests automatically on code changes.
Syntax
JUnit
@Test
public void testMethod() {
    // test code here
}

Each @Test method should not depend on other tests.

Use setup methods like @BeforeEach to prepare fresh data for each test.

Examples
This test checks addition and does not rely on any other test.
JUnit
@Test
public void testAdd() {
    Calculator calc = new Calculator();
    assertEquals(5, calc.add(2, 3));
}
This test checks subtraction independently.
JUnit
@Test
public void testSubtract() {
    Calculator calc = new Calculator();
    assertEquals(1, calc.subtract(3, 2));
}
Sample Program

This example shows two independent tests for add and subtract methods. Each test creates a new Calculator before running. Tests do not share data or depend on each other.

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

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

public class CalculatorTest {
    Calculator calc;

    @BeforeEach
    public void setup() {
        calc = new Calculator();
    }

    @Test
    public void testAdd() {
        assertEquals(5, calc.add(2, 3));
    }

    @Test
    public void testSubtract() {
        assertEquals(1, calc.subtract(3, 2));
    }
}
OutputSuccess
Important Notes

Never share state between tests unless reset before each test.

Independent tests make debugging easier because failures point to exact problems.

Summary

Each test should run alone without relying on others.

Use setup methods to prepare fresh data for every test.

Independent tests improve reliability and clarity.