Unit testing is a software testing method where individual components (units) of a program are tested in isolation. The purpose is to validate that each unit of the software performs as designed. A unit is the smallest testable part of any software, typically a method or function.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CalculatorTest {
@Test
void testAddition() {
Calculator calculator = new Calculator();
assertEquals(4, calculator.add(2, 2));
}
@Test
void testDivision() {
Calculator calculator = new Calculator();
assertEquals(2, calculator.divide(4, 2));
}
}
assertEquals(expected, actual)
- Checks if two values are equalassertTrue(condition)
- Verifies a condition is trueassertFalse(condition)
- Verifies a condition is falseassertNull(object)
- Checks if an object is nullassertNotNull(object)
- Checks if an object is not nullassertThrows(expectedType, executable)
- Verifies that an exception is thrownimport org.junit.jupiter.api.*;
public class TestLifecycleExample {
@BeforeAll
static void setupAll() {
// Runs once before all tests
}
@BeforeEach
void setup() {
// Runs before each test
}
@Test
void testMethod() {
// Test code
}
@AfterEach
void tearDown() {
// Runs after each test
}
@AfterAll
static void tearDownAll() {
// Runs once after all tests
}
}
// MethodName_Scenario_ExpectedResult
@Test
void calculateTotal_WithValidInputs_ReturnsCorrectSum() {
// Test code
}
@Test
void processOrder_WithInvalidQuantity_ThrowsIllegalArgumentException() {
// Test code
}
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.7</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>