14) Testing with JUnit 5 (Basics)
Goal
Learn unit testing fundamentals: arrange/act/assert, naming, and running tests.
Why tests?
- Catch regressions
- Enable refactoring
- Document behavior
JUnit 5 example
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MathUtilTest {
@Test
void add_addsTwoNumbers() {
assertEquals(5, MathUtil.add(2, 3));
}
}
What to test
- Pure logic (easy)
- Edge cases
- Error cases
Avoid testing:
- private methods directly
- trivial getters/setters
Exercises
- Write tests for
isPrime.
- Write tests for
reverse(String) including empty and null handling (decide expected behavior).
Note: this chapter pairs best with the Maven chapter to run tests easily.
Table of contents
- Getting Started: Install, run, and your first program
- Java Basics: types, variables, operators, formatting
- Control Flow: if/switch/loops
- Methods: parameters, return values, overloading
- OOP: classes, objects, encapsulation
- Inheritance & Polymorphism (and when not to use them)
- Interfaces, abstract classes, and design basics
- Exceptions and error handling
- Strings, files, and I/O basics
- Collections: List/Set/Map and Big-O intuition
- Generics (the useful parts)
- Lambdas & Streams
- Dates and time (java.time)
- Testing with JUnit 5 (basics)
- Concurrency: threads, executors, futures
- JVM basics: memory, GC, performance habits
- Build tools: Maven essentials (recommended)
- Next steps: projects to build