Introduction of JUnit

  

JUnit is a unit testing framework for the Java programming language. It plays a crucial role in test-driven development (TDD) and is used to write and run repeatable tests. JUnit belongs to the family of XUnit frameworks, and it is one of the most popular testing libraries in Java.


Key Features of JUnit


FeatureDescription
AnnotationsUses annotations like @Test@BeforeEach@AfterEach@BeforeAll@AfterAll, etc.
AssertionsProvides assertion methods like assertEquals()assertTrue(), etc.
Test RunnerJUnit provides test runners to run test classes individually or as part of a suite.
IntegrationEasily integrates with build tools like Maven/Gradle and IDEs like Eclipse, IntelliJ.



Common JUnit Annotations


AnnotationDescription
@TestMarks a method as a test method
@BeforeEachRuns before each test method
@AfterEachRuns after each test method
@BeforeAllRuns once before all test methods (must be static)
@AfterAllRuns once after all test methods (must be static)
@DisabledSkips a test method or class



Simple Example of JUnit (JUnit 5)

Java Class to Test (Calculator.java)


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

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



Test Class (CalculatorTest.java)


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

public class CalculatorTest {

    Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
        System.out.println("Before Each Test");
    }

    @AfterEach
    void tearDown() {
        System.out.println("After Each Test");
    }

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

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


How to Run JUnit Tests

You can run JUnit tests in several ways:

  • From IDE like Eclipse/IntelliJ (Right-click → Run As → JUnit Test)

  • Using build tools like Maven/Gradle

  • Command line (using javac and java with JUnit jars)



Maven Dependency for JUnit 5

If you're using Maven:


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




Important Points:

  • JUnit helps automate and structure your unit tests.
  • It promotes cleaner code and faster debugging.
  • Easily integrates with CI/CD tools, Maven, and IDEs.
  • Essential for TDD and Agile methodologies.

No comments:

Post a Comment