Testing tooling
Mockito when / thenReturn
Stubs an invocation result. Framework or debugger behavior source-reviewed; actual tool execution NOT RUN.
Formal Syntax & Structure
java syntaxjava
when(catalog.price("B1")).thenReturn(17)Working Example
Example Snippetjava
package example.books;
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;import static org.mockito.Mockito.*;
class CheckoutTest { @Test void pricesFromCatalog() { Catalog catalog = mock(Catalog.class); when(catalog.price("B1")).thenReturn(17); assertEquals(34, new Checkout(catalog).total("B1", 2)); }
@Test void rejectsBeforeCatalogAccess() { Catalog catalog = mock(Catalog.class); assertThrows(IllegalArgumentException.class, () -> new Checkout(catalog).total("B1", -1)); verify(catalog, never()).price("B1"); }}