Dejell
Dejell

Reputation: 14317

Mockito method returns null

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

I have

public class AImpl implements A{

   @Autowired
   B bImpl;

   protected void doSomething(){
      String s = "test";
      String d = b.permuteString(s);
      System.out.println(s.substring(1));
   }

}

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

In the test I have:

@InjectMocks
AImpl aImpl;

@Mock
BImpl bImpl;

@Test
public void testCode(){
testCode(){
   aImpl.doSomething();
}
}

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

Upvotes: 4

Views: 13520

Answers (2)

Alistair A. Israel
Alistair A. Israel

Reputation: 6567

Likely, the B instance being @Autowired into your AImpl instance is also a mock (whether it's a mock B or a mock BImpl, I don't know).

In either case, the default stub method for any mock will probably return null unless you tell it otherwise (unless you stub it).

I can't be certain (unless I run my own tests), but I can say that it'll help for you to simply add logging statements (or use a debugger) to verify whether:

a.) What value does AImpl#b contain (is it a BImpl or a mock B)?

b.) Whether BImpl#permuateString() gets called.

c.) What value BImpl#permuateString() gets for s

Upvotes: 1

GaryF
GaryF

Reputation: 24330

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:

when(bImpl.permuteString("test")).thenReturn("someOtherValue");

Upvotes: 9

Related Questions