First JUnit Test

 

Here's a step-by-step guide to writing your first JUnit test in Eclipse, using JUnit 5 (also known as JUnit Jupiter).


Step 1: Set Up Eclipse Project

  • Open Eclipse.
  • Go to File → New → Java Project.
  • Name the project, example: JUnitDemo.
  • Click Finish.


Step 2: Add JUnit 5 Library

  • Right-click the project → Build Path → Add Libraries.
  • Select JUnit → Click Next.
  • Choose JUnit 5 → Click Finish.


If JUnit 5 is not available, you may need to download JUnit 5 from Maven/Gradle or manually add its .jar files.



Step 3: Create a Class to Test

Create a Java class that has some logic you want to test.


// File: Calculator.java
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}



Step 4: Create a JUnit Test Class

  • Right-click on the src folder → New → JUnit Test Case.
  • Name it CalculatorTest.
  • Select JUnit 5 as the version.
  • Click Finish.



Step 5: Write Your First Test


// File: CalculatorTest.java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {

    @Test
    public void testAddition() {
        Calculator calc = new Calculator();
        int result = calc.add(10, 5);
        assertEquals(15, result, "10 + 5 should equal 15");
    }
}


Step 6: Run the Test

  • Right-click on CalculatorTest.java.
  • Select Run As → JUnit Test.


JUnit 5 Key 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 (static)
@AfterAllRuns once after all test methods (static)
@DisabledDisables a test temporarily


No comments:

Post a Comment