Mockito when method not working

java, mockito

Solution

Mockito mock works when we mock the objects loosely.

Here is the change i have made to make it work:

when(controlWfDefTypeService.getDqCntlWfDefnTypCd(any(DqCntlWfDefn.class))
    .thenReturn(dqCntlWfDefnTyp);

Instead of passing the object of the Mock class, I passed the class with the Matcher `any()` and it works.

Problem

I am using mockito as mocking framework. I have a scenerio here, my when(abc.method()).thenReturn(value) does not return value, instead it returns null. ``` public class DQExecWorkflowServiceImplTest { @InjectMocks DQExecWorkflowServiceImpl dqExecWorkflowServiceImpl = new DQExecWorkflowServiceImpl(); @Mock private DQUtility dqUtility; @Mock private DqExec dqExec; @Mock private DqCntlDefn dqCntlDefn; @Mock private DqCntlWfDefn dqCntlWfDefn; @Mock private DqCntlWfDefnTyp dqCntlWfDefnTyp; @Mock private IDQControlWfDefTypeService controlWfDefTypeService; @Before public void setUp() throws Exception { dqExec = new DqExec(); dqCntlWfDefn = new DqCntlWfDefn(); dqUtility = new DQUtility(); dqCntlWfDefnTyp = new DqCntlWfDefnTyp(); dqCntlWfDefnTyp.setDqCntlWfDefnTypCd("MIN_INCLUSIVE_VAL"); dqExecWorkflowServiceImpl .setControlWfDefTypeService(controlWfDefTypeService); } @Test public void testExecuteWorkflow() { when(controlWfDefTypeService.getDqCntlWfDefnTypCd(dqCntlWfDefn)) .thenReturn(dqCntlWfDefnTyp); dqExecWorkflowServiceImpl.executeWorkflow(dqExec, dqCntlWfDefn); } ``` } Java class ``` @Override public DqCntlWfExec executeWorkflow(final DqExec dqExec, final DqCntlWfDefn dqCntlWfDefn) { final DqCntlWfExec dqCntlWfExec = new DqCntlWfExec(); dqCntlWfExec.setDqCntlWfExecEffDt(dqUtil.getDefaultEffectiveDt()); dqCntlWfExec.setDqCntlWfExecExpDt(dqUtil.getDefaultExpiryDt()); dqCntlWfExec.setDqCntlWfDefn(dqCntlWfDefn); dqCntlWfExec.setDqExec(dqExec); final DqCntlWfDefnTyp dqCntlWfDefnTyp = controlWfDefTypeService .getDqCntlWfDefnTypCd(dqCntlWfDefn); String workflowType = null; if(null!=dqCntlWfDefnTyp){ workflowType = dqCntlWfDefnTyp.getDqCntlWfDefnTypCd(); } ``` When ever i run the test file the when is not working and i am using mockito1.8.5 jar in the buildpath. The service call is being mocked but returns the null value. ``` final DqCntlWfDefnTyp dqCntlWfDefnTyp = controlWfDefTypeService .getDqCntlWfDefnTypCd(dqCntlWfDefn); ``` This object dqCntlWfDefnTyp is null I have done this before and there was no problem with the when, It seems to be working with files i have done before. I had followed the same procedure for the test file but i couldnt figure out the issue. Can anyone please assist me Thanks to all the folks in advance

Original source

Related problems