Java – Mockito method returns null


I looked in the forum but couldn't find why this would happen

I have

public class AImpl implements A{

   B bImpl;

   protected void doSomething(){
      String s = "test";
      String d = b.permuteString(s);


public class BImpl implements B{
    public String permuateString(s){
     return s;

In the test I have:

AImpl aImpl;

BImpl bImpl;

public void testCode(){

The method permuateString from BImpl always returns null. I need to know the result of permuteString() in order to continue the execution of doSomething. so it can't be null

Why is it?

I am using Mockito

Best Solution

By annotating the BImpl field with @Mock, you're saying that the instance itself should be a mock. However, you're not telling Mockito what result the mock should give when invoked with arguments, so Mockito uses its default behaviour of returning null.

The fact that BImpl is a real class with real behaviour is irrelevant. The field does not contain an instance of that class; it contains an instance of a mock.

In your test method, before you call aImpl.doSomething(), tell mockito the behaviour you expect it to use: