Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Mockito.mock(SomeClass) and the @Mock annotation?

What is the difference between Mockito.mock(Class<T> classToMock) method and the @Mock annotation? Are they the same?

For Example, is this:

private TestClass test = Mockito.mock(TestClass.class); 

the same as:

@Mock private TestClass test; 
like image 959
Gábor Csikós Avatar asked May 09 '14 11:05

Gábor Csikós


People also ask

What is the difference between @mock and Mockito mock?

everything started to work as expected. So Mockito. mock is creating a shared mock between the test methods, and @Mock does not.

What does @mock annotation do?

@Mock: It is used to mock the objects that helps in minimizing the repetitive mock objects. It makes the test code and verification error easier to read as parameter names (field names) are used to identify the mocks. The @Mock annotation is available in the org. mockito package.

What is the difference between @mock and @InjectMocks in Mockito framework?

@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance. @Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class.

Which annotation in Mockito is the same as copying the method Mockito mock ()?

Mockito. mock() method and @Mock annotation are doing slightly the same, which is defining a mock object in unit tests.


2 Answers

They both achieve the same result. Using an annotation (@Mock) is usually considered "cleaner", as you don't fill up your code with boilerplate assignments that all look the same.

Note that in order to use the @Mock annotation, your test class should be annotated with @RunWith(MockitoJUnitRunner.class) or contain a call to MockitoAnnotations.initMocks(this) in its @Before method.

like image 139
Mureinik Avatar answered Sep 19 '22 23:09

Mureinik


The difference is in the lines of code you need to write :) :) :)

Seriously though, using the annotations has the exact same effect as using the Mockito.mock.

To quote the documentation of MockitoAnnotations the use of annotations has the following benefits:

  • Allows shorthand creation of objects required for testing.

  • Minimizes repetitive mock creation code.

  • Makes the test class more readable.

  • Makes the verification error easier to read because field name is
    used to identify the mock.

The javadoc for MockitoAnnotations is here

like image 27
geoand Avatar answered Sep 19 '22 23:09

geoand