What You’ll Learn:


1. Unit Testing with JUnit 5

Basic Structure

import org.junit.jupiter.api.*;

class CalculatorTest {

    Calculator calc;

    @BeforeEach
    void setup() {
        calc = new Calculator();
    }

    @Test
    void testAddition() {
        Assertions.assertEquals(5, calc.add(2, 3));
    }

    @AfterEach
    void tearDown() {
        // clean up
    }
}

Annotations:

Annotation Purpose
@Test Marks a test method
@BeforeEach Runs before each test
@AfterEach Runs after each test
@Disabled Skips the test
@Nested Group tests logically

2. Mocking with Mockito

Mockito allows you to create mocks and stubs of dependencies.

Example

@ExtendWith(MockitoExtension.class)
class UserServiceTest {

    @Mock
    private UserRepository repo;

    @InjectMocks
    private UserService service;

    @Test
    void testFindUser() {
        when(repo.findById(1L)).thenReturn(Optional.of(new User(1L, "John")));
        User user = service.findById(1L);
        assertEquals("John", user.getName());
    }
}

Mockito Features:

Method Usage
@Mock Creates mock
@InjectMocks Injects mocks into real object
when(...).thenReturn(...) Stub a method
verify(...) Verify if method was called

3. Integration Testing in Spring Boot