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

Gábor Csikós picture Gábor Csikós · May 9, 2014 · Viewed 22.8k times · Source

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;

Answer

Mureinik picture Mureinik · May 9, 2014

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.