A unit test is code that checks whether a single method or class behaves correctly. Without tests, every change you make could break something, and you won't find out until a user reports a bug.
JUnit is the standard testing framework for Java. Here is a test class:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MathUtilsTest {
@Test
void testAdd() {
assertEquals(5, MathUtils.add(2, 3));
}
}
The @Test annotation marks a method as a test. assertEquals checks that the expected value matches the actual result. If they differ, the test fails with a clear error message showing both values.
Run your tests with Maven (mvn test) or Gradle (gradle test). A passing test suite gives you confidence to refactor without fear.