Mock Working via Proxy
ProductService mockService = mock(ProductService.class);
when(mockService.getProduct(1L))
.thenReturn(new Product(1L, “Laptop”, 999.0));
mock(ProductService.class);
- Uses ByteBuddy or Proxy API to generate a new class dynamically. That class overrides every method of ProductService and injects an interceptor into each one.
So instead of calling your real logic, the generated bytecode looks like:
public Product getProduct(long id) {
return MockHandler.handle(this, “getProduct”, new Object[]{id});
}
So at the JVM level, you literally have a new class definition injected into memory — one that mimics your class but routes all calls through Mockito’s internal handler.
when()
Defines what to do when a mock method is called
.thenReturn()
Specify value to return
.thenThrow()
Specify exception to throw
Example
class UserServiceTest {
@Test
void testGetUserEmail_ReturnsEmail() {
// Arrange
UserRepository repo = mock(UserRepository.class);
UserService service = new UserService(repo);
// Stub behavior
when(repo.findByUsername("john"))
.thenReturn(new User("john", "john@example.com"));
// Act
String email = service.getUserEmail("john");
// Assert
assertEquals("john@example.com", email);
// Verify the interaction happened once
verify(repo, times(1)).findByUsername("john");
}