[英]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. 该方法
permuateString
从BImpl
总是返回null。 I need to know the result of permuteString() in order to continue the execution of doSomething. 我需要知道permuteString()的结果才能继续执行doSomething。 so it can't be null
所以它不能为空
Why is it? 为什么?
I am using Mockito
我正在使用
Mockito
By annotating the BImpl
field with @Mock
, you're saying that the instance itself should be a mock. 通过使用
@Mock
注释BImpl
字段,您说实例本身应该是一个模拟。 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. 但是,你没有告诉Mockito在使用参数调用时模拟应该给出什么结果,所以Mockito使用它返回null的默认行为。
The fact that BImpl
is a real class with real behaviour is irrelevant. BImpl
是一个真实行为的真实类是无关紧要的。 The field does not contain an instance of that class; 该字段不包含该类的实例; it contains an instance of a mock.
它包含一个mock的实例。
In your test method, before you call aImpl.doSomething()
, tell mockito the behaviour you expect it to use: 在您的测试方法中,在调用
aImpl.doSomething()
,请告诉mockito您希望它使用的行为:
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). 可能,@
@Autowired
到你的AImpl
实例中的B
实例也是一个模拟(无论是模拟B
还是模拟BImpl
,我不知道)。
In either case, the default stub method for any mock will probably return null
unless you tell it otherwise (unless you stub
it). 在任何一种情况下,任何模拟的默认存根方法都可能返回
null
除非你另外告诉它(除非你stub
)。
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
)? a。)
AImpl#b
包含什么值(它是BImpl
还是模拟B
)?
b.) Whether BImpl#permuateString()
gets called. b。)是否
BImpl#permuateString()
。
c.) What value BImpl#permuateString()
gets for s
角)什么样的价值
BImpl#permuateString()
获取用于s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.