JAVA TESTING FRAMEWORK
JUnit Tutorial Learn unit testing in Java with test cases, assertions, annotations, and automated execution.
UNIT TESTING Test individual units of Java code.
AUTOMATION Run tests consistently and quickly.
QUALITY Detect defects before release.
What Is JUnit? A foundation for automated unit testing in Java
• JUnit is an open-source testing framework used to write and execute tests for Java applications. • A unit test checks whether a small part of a program behaves as expected. • JUnit helps developers identify defects early and maintain code quality as applications evolve. • JUnit 5 is organized into the JUnit Platform, Jupiter, and Vintage modules.
2
Manual Testing vs Automated Testing Manual Testing
Automated Testing
Tests are executed by a person without automated test tooling.
Tests are executed by a testing framework or tool.
• Can be repetitive • Takes more time at scale • Harder to repeat consistently
• Faster to repeat • Consistent execution • Useful for regression testing
3
Core JUnit Concepts The building blocks of a test
@Test Marks a method as a test method.
Assertions Compare expected results with actual results.
Test Class
Test Runner
Contains related test methods.
Discovers and executes tests.
Lifecycle Setup and cleanup methods can run around tests.
IDE / Build Tool Tests can be launched from common development tools.
4
JUnit Assertions Check whether program behavior matches expectations
• assertEquals(expected, actual) — verifies that two values are equal. • assertTrue(condition) — verifies that a condition is true. • assertFalse(condition) — verifies that a condition is false. • assertNull(value) — verifies that a value is null. • assertNotNull(value) — verifies that a value is not null.
5
JUnit Test Lifecycle Prepare, execute, and clean up tests in a predictable way
Before Each
Test
After Each
Run setup before every test.
Execute the behavior being verified.
Run cleanup after every test.
JUnit 5: @BeforeEach
JUnit 5: @Test
JUnit 5: @AfterEach
Before / After All Run one-time setup or cleanup for a test class.
• JUnit 5 also supports @BeforeAll and @AfterAll for one-time lifecycle operations.
6
Simple JUnit Test Example A small example using a calculator-style method
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class CalculatorTest { @Test void testSum() { int result = 10 + 15; assertEquals(25, result); } }
1. Define Test Use @Test on the method.
2. Run Logic Execute the code being tested.
3. Assert Result Compare expected and actual values.
7
Why Use JUnit? Key takeaways for Java developers
• Automates repeatable unit tests for Java code. • Makes expected behavior explicit through assertions. • Helps catch regressions when code changes. • Supports test lifecycle management and modern IDE/build-tool workflows. • A strong testing foundation improves confidence in application changes.
8