Mockito method returns null
Solution 1
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");
Solution 2
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
Dejell
I like traveling around the world. So far I have been to: USA England Italy Slovania Croatia Jordan South Africa Zimbabwe Botswana France Canada Israel Thailand Switzerland Holland Bulgaria I am going to Vietnam soon
Updated on June 13, 2022Comments
-
Dejell almost 2 years
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
fromBImpl
always returns null. I need to know the result of permuteString() in order to continue the execution of doSomething. so it can't be nullWhy is it?
I am using
Mockito