Mockito桩测试返回null值

4

我正在使用mockito作为模拟框架。我这里有一个场景,我的when(abc.method()).thenReturn(value)没有返回value,而是返回null。

以下是我的类和测试的样子。

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;
}  

现在以下是测试。
@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);
}

使用Mockito的@Mock来模拟存根。测试在foo类中的boolean retrunVal = response.isXXX()附近抛出了NullPointerException。

2个回答

8

对于stub.callingmethod(request).thenReturn(response)的参数匹配器正在进行引用相等性比较。您需要更宽松的匹配器,像这样我认为:

stub.callingmethod(isA(ClassA.class)).thenReturn(response);

0

确保你的 ClassA 实现了自己的 equals 方法并且实现正确。


1
我认为修改等值方法以使参数匹配在单元测试中起作用是不正确的... - Kevin
1
@Kevin,我同意。但是,如果ClassA是他/她自己的类,那么它应该被正确实现。话虽如此,我会选择你的答案而不是我的 :) - Jordan S. Jones

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接