简体   繁体   中英

Mockito keep returning null even after stub

I have some structure like this

...
SomeDao dao = getDAO(AttributeDAO.class);
CustomType type =dao.findByKey(typeOne, typeTwo, typeThree.toString());
if(type == null) {
    System.out.print("null returned");
} else {
    System.out.print("do something");
}
...

My test cases

...
        MainClass mc = Mockito.spy(new MainClass());
        CustomType type = new CustomType();
        SomeDao dao = Mockito.mock(AttributeDAO.class);
        type.setValueOne(1);
        type.setValueTwo(1);
        type.setValueThree("Y");
        Mockito.doReturn(type).when(dao).findByKey(1,2,"Y");

        mc.callThisDaoFunction();
...

But whenever I tried to return the type with eclemma coverage tool it keep saying that type == null how do I my test case or set up for the type to return a non null value?

You need to inject your dao mock to your MainClass . Otherwise it will still try to retrieve the real dao when calling getDao(AttributeDAO.class) .

  • If there is a method setDao it would be just calling it with your mock.
  • Otherwise return dao when mc is invoked with the parameter AttributeDAO.class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM