01 / 21

JUnit
Basics

Learn how to structure and write automated tests in Java using JUnit: the essential framework for verifying your code works correctly.

Java Programming

What Is Automated Testing?

Instead of manually running your program and checking output with your eyes, automated testing means writing small programs that verify your code for you. Each test runs a piece of your code, checks the result, and reports pass or fail instantly.

What Is JUnit?

Framework
JUnit is a Java library that provides annotations, assertions, and a test runner to automate testing.
Industry Standard
Used by millions of Java developers worldwide: from student projects to massive enterprise applications.
JUnit 5
The latest version (also called Jupiter). We will focus on JUnit 5 syntax throughout this lesson.

Why Write Tests?

1
Catch bugs early. Find errors before they reach users or graders.
2
Refactor with confidence. Change your code knowing tests will catch regressions.
3
Document behavior. Tests show exactly what each method is supposed to do.
4
Save time. Running 100 tests takes seconds vs. manually checking each one.

Anatomy of a JUnit Test

1. Import JUnit import org.junit.jupiter.api.*; 2. Create Test Class class CalculatorTest { ... } 3. Annotate with @Test @Test void shouldAddTwoNumbers() { ... } 4. Assert Expected Results assertEquals(expected, actual);

Core Annotations

@Test
Marks a method as a test case. JUnit will discover and run it automatically.
@BeforeEach
Runs before every test method: use it to set up fresh objects for each test.
@AfterEach
Runs after every test method: use it to clean up resources like files or connections.

Key Assertion Methods

Method What It Checks
assertEquals(a, b) a equals b
assertNotEquals(a, b) a does not equal b
assertTrue(cond) condition is true
assertFalse(cond) condition is false
assertNull(obj) object is null
assertThrows(E, code) code throws exception E

@Test vs. main()

JUnit @Test main() Method
Discovery Automatic Must call manually
Isolation Each test runs independently Shared state, order-dependent
Reporting Pass/fail per method Crashes or prints to console
Scalability Runs hundreds in seconds Tedious to maintain

How to Write a Test

1
Arrange: Create objects and set up the data you need for the test.
2
Act: Call the method you want to test with your prepared inputs.
3
Assert: Compare the actual result to the expected result using an assertion.

Example 1: Simple Test

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

class CalculatorTest {

    @Test
    void shouldAddTwoNumbers() {
        // Arrange
        Calculator calc = new Calculator();

        // Act
        int result = calc.add(3, 7);

        // Assert
        assertEquals(10, result);
    }
}

Example 2: @BeforeEach Setup

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

class CalculatorTest {
    private Calculator calc;

    @BeforeEach
    void setUp() {
        calc = new Calculator();  // fresh instance each test
    }

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

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

Example 3: Testing Exceptions

@Test
void shouldThrowOnDivideByZero() {
    Calculator calc = new Calculator();

    assertThrows(
        ArithmeticException.class,
        () -> calc.divide(10, 0)
    );
}

Test Lifecycle Flow

@BeforeAll Repeat for each @Test method @BeforeEach @Test method @AfterEach @AfterAll

Test Naming Conventions

should___When___
shouldReturnZeroWhenEmptyList() : describes expected behavior and condition.
method_scenario_result
add_negativeNumbers_returnsNegative() : names the method, scenario, and outcome.

One Behavior Per Test

Each test method should verify exactly one behavior. If you find yourself writing multiple unrelated assertions in one method, split them into separate tests.

// BAD: testing two behaviors at once
@Test
void testCalculator() {
    assertEquals(5, calc.add(2, 3));
    assertEquals(1, calc.subtract(3, 2)); // unrelated!
}

// GOOD: one behavior per test
@Test void testAdd() { assertEquals(5, calc.add(2, 3)); }
@Test void testSubtract() { assertEquals(1, calc.subtract(3, 2)); }

Common Mistakes

✕ Forgetting @Test
Without the annotation, JUnit ignores the method completely: it simply never runs.
✕ Swapped Arguments
assertEquals(expected, actual): put expected first. Swapping gives confusing failure messages.
✕ Tests Depend on Order
Tests that share mutable state or rely on running in a specific order are fragile and unreliable.

Question 1 of 5

Which annotation marks a method as a test case in JUnit 5?

Question 2 of 5

In assertEquals(expected, actual), what is the correct order of arguments?

Question 3 of 5

What does @BeforeEach do?

Question 4 of 5

Which assertion checks that code throws a specific exception?

Question 5 of 5

What is the main problem with this test?