Difference between @Mock and @InjectMocks

user2249972 picture user2249972 · May 9, 2013 · Viewed 292.1k times · Source

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

Answer

Tom Verelst picture Tom Verelst · May 9, 2013

@Mock creates a mock. @InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock (or @Spy) annotations into this instance.

Note that you must use @RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this) to initialize these mocks and inject them.

@RunWith(MockitoJUnitRunner.class)
public class SomeManagerTest {

    @InjectMocks
    private SomeManager someManager;

    @Mock
    private SomeDependency someDependency; // this will be injected into someManager

     //tests...

}