# Mockito Basics — Advanced Java

Source: https://www.geekswithgeeks.com/en/advanced-java/adv-mockito-basics

> Isolate the class under test by replacing its real collaborators with Mockito mocks, stub their behaviour with when/thenReturn, and verify interactions.

## Stub a dependency

`mock(Type.class)` creates a fake implementation with no real behaviour; `when(...).thenReturn(...)` programs what it should return for a given call. The class under test is real — only its dependency is faked.

```java
@Test
void appliesDiscountFromRepo() {
    DiscountRepository repo = mock(DiscountRepository.class);
    when(repo.findByCode("SAVE10")).thenReturn(Optional.of(new Discount(10)));

    PriceService svc = new PriceService(repo);
    assertEquals(90, svc.total(100, "SAVE10"));
}
```

## verify and argument matchers

`verify(mock).method(args)` asserts an interaction actually happened — essential when the method under test returns `void` and its whole effect is calling a collaborator. `any()`, `anyInt()`, `eq()` match arguments loosely when the exact value doesn't matter.

```java
@Test
void sendsReceiptOnPlaceOrder() {
    EmailSender sender = mock(EmailSender.class);
    OrderService svc = new OrderService(sender);

    svc.place(new Order("A1", 3));

    verify(sender).send(eq("A1"), anyString());
}
```
