In this post, we will learn about difference between Mock, MockBean and MockIto.mock methods. This will very confusing to the developers and even I also faced some times. Lets go to the details:
- Mock and Mockito.mock() are both used to create a mock object in a test written with the Mockito framework. They are used in different ways, but serve the same purpose.
- @Mock is a JUnit annotation that can be used to create a mock object and inject it into a test class field. It is typically used in combination with the @RunWith(MockitoJUnitRunner.class) annotation to run the test using the Mockito test runner.
- Mockito.mock() is a static method in the Mockito class that can be used to create a mock object. It can be used in any test method and does not require any specific test runner to be used.
- @MockBean is a Spring annotation that can be used to create a mock object and register it as a bean in the Spring application context. It allows for the mock to be used as a dependency in other beans within the context.
So, @Mock is for JUnit test and @MockBean is for Spring Application context.
MockIto Example Code:
public class PaymentServiceTest {
@MockBean
private PaymentServiceImpl paymentService;
@Mock
private BankService bankService;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
//with mock
PaymentServiceImpl paymentService = Mockito.mock(PaymentServiceImpl.class);
}
@Test
public void testTransfer() {
}
}
Thanks for Reading…