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
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
- Arrange: set up the data.
- Act: call the method.
- Assert: check the result.
Parameterized tests
@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):
<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
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:
@RestController
class HelloController {
@GetMapping("/hello")
String hello() { return "Hello from Java ☕"; }
}
Example
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