title: When should we use @InjectMocks?
body: <p>I have read through a lot of discussion about @Mock &amp; @InjectMocks and still could not find what are the suitable or necessary cases to use @InjectMocks. In fact, I am not sure about what would happen when we use @InjectMocks.</p>
  
  <p>Consider the following example,</p>
  
  <pre><code>public class User {
    private String user_name;
    private int user_id;
    public User(int user_id) {
      this.user_id = user_id;
    }
    public String getUser_name() {
      return user_name;
    }
    public void setUser_name(String user_name) {
      this.user_name = user_name;
    }
    public int getUser_id() {
      return user_id;
    }
    public void setUser_id(int user_id) {
      this.user_id = user_id;
    }     
  }
  
  public interface UserDao {
    public List&lt;User&gt; getUserList();
  }
  
  public class UserService {
    private UserDao userDao;  
    public UserDao getUserDao() {
      return userDao;
    }
    public void setUserDao(UserDao userDao) {
      this.userDao = userDao;
    }
    public List&lt;User&gt; getUserList() {
      return userDao.getUserList();
    }
  }
  </code></pre>
  
  <p>This is my test class</p>
  
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  public class UserServiceTest {  
    private UserService service = new UserService();
    @Mock
    private UserDao dao;
  
    @Test
    public void testGetUserList() {
  
      service.setUserDao(dao);
  
      // mock the return value of the mock object
      List&lt;User&gt; mockResult = Arrays.asList(new User(101),new User(102),new User(103));       
      when(dao.getUserList()).thenReturn(mockResult);
  
      // check return value is same as mocked value
      assertEquals(service.getUserList(),mockResult);
  
      // verify the getUserList() function is called
      verify(dao).getUserList();  
    }
  }    
  </code></pre>
  
  <p>The test run successfully with no errors.
  Consider another approach using @InjectMock annotation.</p>
  
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  public class UserServiceTest {  
  
    @InjectMocks
    private UserService service;
    @Mock
    private UserDao dao;
  
    @Test
    public void testGetUserList() {
  
      service.setUserDao(dao);
  
      // mock the return value of the mock object
      List&lt;User&gt; mockResult = Arrays.asList(new User(101),new User(102),new User(103));       
      when(dao.getUserList()).thenReturn(mockResult);
  
      // check return value is same as mocked value
      assertEquals(service.getUserList(),mockResult);
  
      // verify the getUserList() function is called
      verify(dao).getUserList();  
    }
  }    
  </code></pre>
  
  <p>This works equally well. So, which way is better? Any best practice? 
  Btw, I am using Junit 4.8.1 and Mockito 1.9.5</p>