Test Overview
This test verifies that advanced mocking can handle complex dependencies by simulating interactions between multiple dependent objects in a service method.
This test verifies that advanced mocking can handle complex dependencies by simulating interactions between multiple dependent objects in a service method.
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class OrderServiceTest { @Mock InventoryService inventoryService; @Mock PaymentService paymentService; @InjectMocks OrderService orderService; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); } @Test void testPlaceOrder_Success() { // Arrange String productId = "prod123"; int quantity = 2; when(inventoryService.isAvailable(productId, quantity)).thenReturn(true); when(paymentService.charge(anyDouble())).thenReturn(true); // Act boolean result = orderService.placeOrder(productId, quantity, 50.0); // Assert assertTrue(result); verify(inventoryService).isAvailable(productId, quantity); verify(paymentService).charge(50.0); } } // Supporting classes class OrderService { private final InventoryService inventoryService; private final PaymentService paymentService; public OrderService(InventoryService inventoryService, PaymentService paymentService) { this.inventoryService = inventoryService; this.paymentService = paymentService; } public boolean placeOrder(String productId, int quantity, double amount) { if (!inventoryService.isAvailable(productId, quantity)) { return false; } return paymentService.charge(amount); } } interface InventoryService { boolean isAvailable(String productId, int quantity); } interface PaymentService { boolean charge(double amount); }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Mockito annotations are initialized | Mocks for InventoryService and PaymentService are created and injected into OrderService | - | PASS |
| 2 | Test calls orderService.placeOrder with productId 'prod123', quantity 2, amount 50.0 | OrderService calls inventoryService.isAvailable with 'prod123' and 2 | - | PASS |
| 3 | Mocked inventoryService returns true for availability | OrderService proceeds to call paymentService.charge with 50.0 | - | PASS |
| 4 | Mocked paymentService returns true for charge | OrderService returns true indicating order placed successfully | assertTrue(result) verifies order placement success | PASS |
| 5 | Verify inventoryService.isAvailable was called with correct parameters | Verification passes confirming interaction | verify(inventoryService).isAvailable(productId, quantity) | PASS |
| 6 | Verify paymentService.charge was called with correct amount | Verification passes confirming interaction | verify(paymentService).charge(50.0) | PASS |