Mockito when method not working

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.


I think I have found your issue, but not all the credit goes to me.

Since you are trying to mock 'dqCntlWfDefnTyp' in your test class and the object itself is being instantiated in the class that you are trying to test, you inevitably run into some issues. The primary problem is that the object cannot be mocked because it is being recreated in during the test.

There are a few options, but the best choice in my humble opinion is using PowerMockito. You will be able to replace the object within the class that is being tested with the one you mock.

An excellent example of this usage of PowerMockito from @raspacorp on this question:

public class MyClass {
void method1{
    MyObject obj1=new MyObject();
    obj1.method1();
}
}

And the test class...

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
@Test
public void testMethod1() {      
    MyObject myObjectMock = mock(MyObject.class);
    when(myObjectMock.method1()).thenReturn(<whatever you want to return>);   
    PowerMockito.whenNew(MyObject.class).withNoArguments().thenReturn(myObjectMock);

    MyClass objectTested = new MyClass();
    objectTested.method1();

    ... // your assertions or verification here 
}
}

TL;DR If some arguments in your test are null, be sure to mock the parameter call with isNull() instead of any(SomeClass.class).


Explanation

This might not be the answer that helps OP, but might be useful for someone else. In my case the setup was all good, however, some mocks returned the desired thenReturn(...) value and some didn't.

It's important to understand, that the method call you're trying to mock (i.e. the method in when(someMock.methodToMock)) has to match the actual call and not the signature only.

In my case, I mocked a method with a signature:

public void SomeValue method(String string, SomeParam param)

The call however, in the test was something like:

method("some string during test", null);

Now if you mock the call with:

when(MockedClass.method(anyString(), any(SomeParam.class))

Mockito will not match it even though the signature is correct. The problem is that Mockito is looking for a call of method() with the arguments String and SomeParam, whereas the actual call was with a String and null. What you have to do is:

when(MockedClass.method(anyString(), isNull())

Hint

Since there are many isNull() implementations in different frameworks, be sure to use this one org.mockito.ArgumentMatchers.isNull.


I had the same problem. The solution for me was to put the Mockito.when(...).thenReturn(...); into the @Before-SetUp method.

Tags:

Java

Mockito