BAEL-5889: Added code for Spy and SpyBean difference implementation
This commit is contained in:
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.spytest;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.SpyBean;
|
||||
|
||||
@SpringBootTest
|
||||
class OrderServiceIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
OrderRepository orderRepository;
|
||||
@SpyBean
|
||||
NotificationService notificationService;
|
||||
@SpyBean
|
||||
OrderService orderService;
|
||||
|
||||
@Test
|
||||
void givenNotificationServiceIsUsingSpyBean_whenOrderServiceIsCalled_thenNotificationServiceSpyBeanShouldBeInvoked() {
|
||||
|
||||
Order orderInput = new Order(null, "Test", 1.0, "17 St Andrews Croft, Leeds ,LS17 7TP");
|
||||
Order order = orderService.save(orderInput);
|
||||
Assertions.assertNotNull(order);
|
||||
Assertions.assertNotNull(order.getId());
|
||||
verify(notificationService).notify(any(Order.class));
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.spytest;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Spy;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
@ExtendWith(SpringExtension.class)
|
||||
class OrderServiceUnitTest {
|
||||
|
||||
@Spy
|
||||
OrderRepository orderRepository;
|
||||
@Spy
|
||||
NotificationService notificationService;
|
||||
@InjectMocks
|
||||
OrderService orderService;
|
||||
|
||||
@Test
|
||||
void givenNotificationServiceIsUsingSpy_whenOrderServiceIsCalled_thenNotificationServiceSpyShouldBeInvoked() {
|
||||
|
||||
UUID orderId = UUID.randomUUID();
|
||||
Order orderInput = new Order(orderId, "Test", 1.0, "17 St Andrews Croft, Leeds ,LS17 7TP");
|
||||
doReturn(orderInput).when(orderRepository)
|
||||
.save(any());
|
||||
Order order = orderService.save(orderInput);
|
||||
Assertions.assertNotNull(order);
|
||||
Assertions.assertEquals(orderId, order.getId());
|
||||
verify(notificationService).notify(any(Order.class));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user