# Creating Mocks and Stubbing — JUnit 5 & Mockito

Source: https://www.skillbyai.com/en/java-testing/m-basics

> Create mocks with @Mock and @InjectMocks and stub methods with when/thenReturn.

## Mockito in a JUnit test

Mockito creates **mock objects** of interfaces and classes. Create them with **`mock(Type.class)`**, or declaratively with **`@Mock`** fields in a test class annotated **`@ExtendWith(MockitoExtension.class)`**, which also enables **strict stubs**. **`@InjectMocks`** creates the class under test and injects the mocks through its constructor (or setters and fields), although many teams prefer creating the object explicitly with `new` for clarity. Unstubbed methods return **default values**: `null` for objects, 0 for numbers, `false`, empty collections and `Optional.empty()`. **Stub** behaviour with **`when(mock.method(args)).thenReturn(value)`**, chain several values (`thenReturn(a, b)`) for consecutive calls, or **`thenThrow(exception)`** to simulate failures. Since Mockito 5, the **inline mock maker** is the default, so final classes and methods can be mocked too. With MockitoExtension's strictness, a stub that the test never uses raises **`UnnecessaryStubbingException`**, keeping tests clean and catching copy-paste mistakes.

## A service test with mocks

Mocks supply data and simulate a failure; the test checks the result.

```java
@ExtendWith(MockitoExtension.class)
class PriceQuoteServiceTest {

    @Mock ProductCatalog catalog;
    @Mock TaxService tax;

    PriceQuoteService service;

    @BeforeEach
    void setUp() {
        service = new PriceQuoteService(catalog, tax);    // explicit construction
    }

    @Test
    void quoteAddsTax() {
        when(catalog.priceOf("pen")).thenReturn(new BigDecimal("100.00"));
        when(tax.rateFor("pen")).thenReturn(new BigDecimal("0.18"));

        Quote q = service.quote("pen", 2);

        assertThat(q.total()).isEqualByComparingTo("236.00");
    }

    @Test
    void unknownProductIsReported() {
        when(catalog.priceOf("ghost")).thenThrow(new ProductNotFoundException("ghost"));

        assertThatThrownBy(() -> service.quote("ghost", 1))
            .isInstanceOf(ProductNotFoundException.class);
    }
}
```

## An actor reading lines

A mock is an understudy actor who knows only the lines you hand them: ask about the price of a pen and they say "100". Ask anything else and they say nothing useful, which is exactly what you want in a controlled rehearsal.

**Quiz:** What does an unstubbed Mockito mock method returning List<String> return by default?

- [ ] null
- [x] An empty list
- [ ] A list with one element
- [ ] It throws an exception

*Answer:* An empty list. Mockito returns sensible empty defaults for collections, Optionals and primitives.
