Gopinathan Gopinathan - 10 months ago 62
Java Question

Mockito when method not working

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 {
DQExecWorkflowServiceImpl dqExecWorkflowServiceImpl = new DQExecWorkflowServiceImpl();
private DQUtility dqUtility;
private DqExec dqExec;
private DqCntlDefn dqCntlDefn;
private DqCntlWfDefn dqCntlWfDefn;
private DqCntlWfDefnTyp dqCntlWfDefnTyp;
private IDQControlWfDefTypeService controlWfDefTypeService;

public void setUp() throws Exception {
dqExec = new DqExec();
dqCntlWfDefn = new DqCntlWfDefn();
dqUtility = new DQUtility();
dqCntlWfDefnTyp = new DqCntlWfDefnTyp();


public void testExecuteWorkflow() {
dqExecWorkflowServiceImpl.executeWorkflow(dqExec, dqCntlWfDefn);


Java class

public DqCntlWfExec executeWorkflow(final DqExec dqExec,
final DqCntlWfDefn dqCntlWfDefn) {
final DqCntlWfExec dqCntlWfExec = new DqCntlWfExec();

final DqCntlWfDefnTyp dqCntlWfDefnTyp = controlWfDefTypeService
String workflowType = null;
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

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


Mockito mock works when we mock the objects loosely.

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


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