javaintermediate
Mockito — Mocking and Verification
Mock dependencies with Mockito: when/thenReturn, verify, argument captors, and spy patterns.
javaPress ⌘/Ctrl + Shift + C to copy
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Optional;
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock UserRepository userRepo;
@Mock PaymentGateway paymentGateway;
@Mock EmailService emailService;
@InjectMocks OrderService orderService;
@Captor ArgumentCaptor<String> emailCaptor;
@Test
void shouldPlaceOrder() {
// Given
var user = new User(1L, "Alice", "alice@test.com");
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
when(paymentGateway.charge(anyDouble())).thenReturn(true);
// When
Order order = orderService.placeOrder(1L, 99.99);
// Then
assertNotNull(order);
assertEquals("CONFIRMED", order.status());
// Verify interactions
verify(userRepo).findById(1L);
verify(paymentGateway).charge(99.99);
verify(emailService).sendConfirmation(emailCaptor.capture(), any());
assertEquals("alice@test.com", emailCaptor.getValue());
// Never called with wrong args
verify(paymentGateway, never()).refund(anyDouble());
}
@Test
void shouldThrowWhenUserNotFound() {
when(userRepo.findById(999L)).thenReturn(Optional.empty());
assertThrows(ResourceNotFoundException.class,
() -> orderService.placeOrder(999L, 50.0));
verifyNoInteractions(paymentGateway, emailService);
}
@Test
void shouldRetryPayment() {
var user = new User(1L, "Bob", "bob@test.com");
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
when(paymentGateway.charge(anyDouble()))
.thenThrow(new RuntimeException("Timeout"))
.thenReturn(true); // succeeds on retry
Order order = orderService.placeOrder(1L, 50.0);
assertEquals("CONFIRMED", order.status());
verify(paymentGateway, times(2)).charge(50.0);
}
}Use Cases
- Testing service layers with mocked dependencies
- Verifying method calls and argument values
- Testing retry and error handling logic
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
javaintermediate
JUnit 5 — Test Patterns and Assertions
Write JUnit 5 tests with assertions, lifecycle hooks, nested tests, parameterized tests, and dynamic tests.
Best for: Unit testing Java applications with JUnit 5
#java#junit
kotlinintermediate
Testing with MockK Framework
Mock dependencies in Kotlin tests with MockK: relaxed mocks, verify, coEvery, and slot captures.
Best for: Unit testing with mocked dependencies
#kotlin#testing
javabeginner
Reverse a String in Java
Multiple ways to reverse a string in Java including StringBuilder, char array, and stream approaches.
Best for: String manipulation in coding interviews
#java#string
javabeginner
Read File Line by Line in Java
Read files using BufferedReader, Files.readAllLines, and Stream API with proper resource management.
Best for: Processing log files line by line
#java#file-io