...

What is the Difference between @Mock, @MockBean and Mockito.mock()?

@Mock, Mockito.mock(), and @MockBean are all related to creating mock objects for testing, but they are used in different contexts and frameworks. Let’s break down the differences:

What is @Mock?

  • @Mock is an annotation provided by the Mockito framework.
  • It is used in conjunction with a testing framework like JUnit or TestNG.
  • @Mock is used to create a mock object, but you need to initialize it before using it in tests. Example:
   import org.mockito.Mock;

   // ...

   @Mock
   private MyService myService;

What is Mockito.mock()?

  • Mockito.mock() is a method provided by the Mockito framework.
  • It is used to manually create a mock object when you are not using annotations or when you need more control over the creation of the mock.
  • It is often used in conjunction with JUnit or TestNG tests. Example:
   import static org.mockito.Mockito.mock;

   // ...

   MyService myService = mock(MyService.class);

What is @MockBean?

  • @MockBean is a Spring Boot annotation.
  • It is used in integration tests (generally @SpringBootTest) to replace a real bean with a mock within the Spring context.
  • @MockBean is specifically designed for use in the Spring context, allowing you to replace a real bean with a Mockito mock during the testing of Spring components. Example:
   import org.springframework.boot.test.mock.mockito.MockBean;

   // ...

   @SpringBootTest
   public class MyServiceTest {

       @MockBean
       private MyService myService;
   }

@Mock and Mockito.mock() are from the Mockito framework and are generally used in non-Spring testing scenarios. They are equivalent way to mock an object.

On the other hand, @MockBean is a Spring Boot annotation specifically designed for replacing beans with mocks in the Spring context during integration tests. Choose the one that aligns with your testing framework and context.

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.