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
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");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With