Java · Module 12 · Lesson 21 min read

Testing & Build Tools

Why test?

Automated tests check your code in seconds every time you change it. They catch bugs early and let you refactor without fear.

JUnit 5 basics

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

class CalculatorTest {
    Calculator calc;

    @BeforeEach
    void setUp() { calc = new Calculator(); }    // runs before every test

    @Test
    @DisplayName("2 + 3 should be 5")
    void addsNumbers() {
        assertEquals(5, calc.add(2, 3));
    }

    @Test
    void divideByZeroThrows() {
        assertThrows(ArithmeticException.class, () -> calc.divide(1, 0));
    }
}

Common assertions: assertEquals, assertTrue, assertFalse, assertNull, assertNotNull, assertThrows.

Arrange – Act – Assert

  1. Arrange: set up the data.
  2. Act: call the method.
  3. Assert: check the result.

Parameterized tests

Java
@ParameterizedTest
@ValueSource(ints = {2, 4, 6})
void evenNumbers(int n) { assertTrue(n % 2 == 0); }

Build tools

They download libraries, compile, test and package your app.

Maven (pom.xml):

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

Commands: mvn test, mvn package

Gradle (build.gradle): testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2' Commands: ./gradlew test, ./gradlew build

Standard project layout

CSS
src/main/java   → your code
src/test/java   → your tests

Next step: Spring Boot 🌱

The most popular Java framework for web APIs. Generate a project at start.spring.io, then:

Java
@RestController
class HelloController {
    @GetMapping("/hello")
    String hello() { return "Hello from Java ☕"; }
}

Example

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

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

class CalculatorTest {
    private final Calculator calc = new Calculator();

    @Test
    void addsTwoNumbers() {
        // Arrange + Act
        int result = calc.add(2, 3);
        // Assert
        assertEquals(5, result);
    }

    @Test
    void dividingByZeroThrows() {
        assertThrows(ArithmeticException.class, () -> calc.divide(10, 0));
    }
}
// Run with: mvn test  ✅ 2 tests passed