java mockito 存根返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6205013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mockito stubbing returns null
提问by Ritesh Mengji
I am using mockito as mocking framework. I have a scenerio here, my when(abc.method()).thenReturn(value) does not return value, instead it returns null.
我使用 mockito 作为模拟框架。我这里有一个场景,我的 when(abc.method()).thenReturn(value) 不返回值,而是返回 null。
Here is how my class and test looks like.
这是我的课程和测试的样子。
public class foo(){
public boolean method(String userName) throws Exception {
ClassA request = new ClassA();
request.setAbc(userName);
ClassB response = new ClassB();
try {
response = stub.callingmethod(request);
} catch (Exception e) {
}
boolean returnVal = response.isXXX();
return returnVal;
}
Now follwoing is the test
现在下面是测试
@Test
public void testmethod() throws Exception{
//arrange
String userName = "UserName";
ClassA request = new ClassA();
ClassB response = new ClassB();
response.setXXX(true);
when(stub.callingmethod(request)).thenReturn(response);
//act
boolean result = fooinstance.lockLogin(userName);
//assert
assertTrue(result);
}
stub is mocked using mockito i.e using @Mock. The test throws NullPointerException in class foo near boolean retrunVal = response.isXXX();
stub 使用 mockito 进行模拟,即使用 @Mock。该测试在 boolean retrunVal = response.isXXX(); 附近的 foo 类中抛出 NullPointerException;
回答by Kevin
the argument matcher for stub.callingmethod(request).thenReturn(response) is comparing for reference equality. You want a more loose matcher, like this I think:
stub.callingmethod(request).thenReturn(response) 的参数匹配器正在比较参考相等性。你想要一个更松散的匹配器,我认为是这样的:
stub.callingmethod(isA(ClassA.class)).thenReturn(response);
回答by Jordan S. Jones
Ensure that your ClassA
implements its own equals
and that it is correctly implemented.
确保您自己ClassA
实施equals
并正确实施。