- What is unit testing?
It is the testing of one small piece of logic (a unit), such as a method or a class (without DB, HTTP, or other external dependencies). It documents the expected behavior of the code.
- Why tests are important: locally and globally
Local benefits:
Quickly check that everything works. Enable safe refactoring (changing code without changing behavior): 20 lines → 5 lines → run tests → OK → commit. Detect bugs during development, not during testing, CI, or production. If a test runs longer than 1 second, it’s usually too slow.
Global benefits:
Define and document code behavior (expectations and logic), e.g. shouldThrowExceptionWhenUserNotFound(). Ensure important edge cases are covered. Provide regression safety. Improve CI stability (unit tests for each pipeline).
- How unit tests look in the project structure
Required setup and configuration. Maven: project structure, test dependencies, and build lifecycle. Maven repository example: https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api/5.9.1 JUnit (IntelliJ support, e.g. Alt+Enter to create tests).
- How to write tests JUnit annotations:
@Test @BeforeEach @AfterEach @BeforeAll @AfterAll
Test structure patterns:
given / when / then Arrange – Act – Assert (AAA) Example: Calculator
Assertions: assertEquals(expected, actual); assertTrue(condition); assertNotNull(obj); assertThrows(Exception.class, () -> service.call());
1 assertion = 1 check Test both successful and unsuccessful cases.
Naming tests: Format: methodName_condition_expectedResult Exception testing: Covered with assertThrows(...).
- Stub vs. Mock (Mockito) Use stubs or mocks when your class depends on external systems such as:
databases REST services other services
Unit tests vs. integration tests:
Unit tests: test logic in isolation. Integration tests: test interactions between components.
- TDD (Test-Driven Development) Cycle: Test → Code → Refactor