Reputation: 85
I have a DAO method which returns a List.
Now I am trying to mock this DAO class in my service layer but when I invoke the DAO method, it is giving me a empty even though I have mocked the DAO method Below is the sample code snippet,
public class ABCTest {
@InjectMocks
ABC abc = new ABC();
@Mock
private ABCDao dao;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
dao = Mockito.mock(ABCDao.class);
Mockito.when(dao.getListFromDB()).thenReturn(Arrays.asList("1","2","3"));
}
@Test
public void testServiceMethod() {
abc.serviceMethod(); // Inside this method when the DAO method is called, it is giving me an empty list even though I have mocked it above.
}
Any pointers would be helpful
Upvotes: 0
Views: 2512
Reputation: 27996
MockitoAnnotations.initMocks(this);
use @RunWith(MockitoJunitRunner.class)
insteaddao = Mockito.mock(ABCDao.class)
which overrides the dao
created by MockitoAnnotations.initMocks(this)
ABCDao
instance inside ABC is now different to the dao
member of your test case.I can only assume that the following would fail:
assertTrue(dao == abc.getDao())
Solution: Remove the following line
dao = Mockito.mock(ABCDao.class);
Upvotes: 1