I am new to Mockito. I am trying to write jnuit for a service by mocking the db interactions:
I have following classes (just representative of actual classes)
public class TestService{
public Response getTestList(String type){
list = getListbyType(type);
return response.entity(list);
}
private List getListbyType(String type){
...
..
TestDAO testdao = new Testdao(sqlconn);
list = testdao.getListfromDB(type)
return list;
}
}
And my test class is something like
public class TestServiceTest{
@InjectMocks
private TestService testService = new TestService();
@Test
public void getTestListTest(){
List testlist = new List();
tetslist.add("test1");
TestDAO testdaomock = mock(TestDAO);
when(testdaomock.getListfromDB("test")).thenreturn(list);
list = testService.getTestList(test);
}
}
But when I run this test, it still invokes the actual DB call and retrieves the values from db and not the mocked values, should I mock sql connection and non default constructor? I am clueless.
-- UPDATE
As people have suggested, I moved DAO instantiation to my service constructor and also used Spy, But still my actual DB call is invoked instead of the mock call.
testdaomock.getListfromDB("test")should not compile becauseprivate List getListbyType(String type)is private. How does it compile? - user3458@RunWith(MockitoJUnitRunner.class)- WildDev