JUnit

JUnit is a popular testing framework in Java used to write and run unit tests. It helps you test individual units (like methods) of your code to ensure they work as expected.

Here’s a simple example using JUnit 5 (latest version):


1. Add JUnit dependency

If you’re using Maven, add this to your pom.xml:

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.10.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

2. Sample Java class to test

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

    public int subtract(int a, int b) {
        return a - b;
    }
}

3. JUnit test class

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

class CalculatorTest {

    @Test
    void testAdd() {
        Calculator calc = new Calculator();
        int result = calc.add(5, 3);
        assertEquals(8, result);  // Checks if result is 8
    }

    @Test
    void testSubtract() {
        Calculator calc = new Calculator();
        int result = calc.subtract(5, 3);
        assertEquals(2, result);  // Checks if result is 2
    }
}

4. Run the tests

  • In IDE: Right-click on CalculatorTest → Run.
  • Using Maven: mvn test

If the methods return the expected results, the tests pass. Otherwise, JUnit will show which test failed.


✅ Key Points:

  • @Test annotation marks a method as a test method.
  • assertEquals(expected, actual) checks if values match.
  • You can also use assertTrue, assertFalse, assertThrows, etc. for different checks.

Leave a Reply