0
0
JunitHow-ToBeginner ยท 4 min read

How to Set Up JUnit in Java for Unit Testing

To set up JUnit in Java, add the JUnit library to your project dependencies (e.g., via Maven or Gradle). Then, create test classes with methods annotated by @Test to write and run your unit tests.
๐Ÿ“

Syntax

JUnit tests use the @Test annotation to mark methods as test cases. You import org.junit.jupiter.api.Test for JUnit 5. Assertions check expected results using methods like Assertions.assertEquals().

Typical parts:

  • @Test: marks a method as a test
  • Test method: contains code to test functionality
  • Assertions: verify expected outcomes
java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class ExampleTest {
    @Test
    void testAddition() {
        int sum = 2 + 3;
        assertEquals(5, sum);
    }
}
๐Ÿ’ป

Example

This example shows a simple JUnit 5 test class that checks if addition works correctly. It uses @Test and assertEquals to verify the sum.

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

public class CalculatorTest {
    @Test
    void addsTwoNumbers() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 3);
        assertEquals(5, result, "2 + 3 should equal 5");
    }
}

class Calculator {
    int add(int a, int b) {
        return a + b;
    }
}
Output
Test passed: addsTwoNumbers
โš ๏ธ

Common Pitfalls

  • Forgetting to add JUnit dependency to your project causes compilation errors.
  • Using @Test from JUnit 4 (org.junit.Test) instead of JUnit 5 (org.junit.jupiter.api.Test).
  • Not making test methods void and parameterless.
  • Missing static import for assertions leads to verbose code.
java
/* Wrong: Missing @Test annotation */
public class WrongTest {
    void testSomething() {
        assertEquals(4, 2 + 2);
    }
}

/* Right: Correct @Test annotation and imports */
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class RightTest {
    @Test
    void testSomething() {
        assertEquals(4, 2 + 2);
    }
}
๐Ÿ“Š

Quick Reference

StepDescription
Add JUnit dependencyInclude JUnit 5 in your build tool (Maven/Gradle)
Import JUnit classesImport @Test and assertions from JUnit 5 packages
Write test methodsCreate methods annotated with @Test that are void and parameterless
Use assertionsCheck expected results with assertEquals, assertTrue, etc.
Run testsUse IDE or build tool to run tests and see results
โœ…

Key Takeaways

Add JUnit 5 dependency to your project before writing tests.
Use @Test annotation from org.junit.jupiter.api for test methods.
Test methods must be void and have no parameters.
Use assertions like assertEquals to verify expected outcomes.
Run tests via IDE or build tool to check pass/fail results.