Mockito Flashcards

(5 cards)

1
Q

Mock Working via Proxy

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

when()

A

Defines what to do when a mock method is called

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

.thenReturn()

A

Specify value to return

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

.thenThrow()

A

Specify exception to throw

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Example

A

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");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly