【问题标题】:mockito stubbing returns nullmockito 存根返回 null
【发布时间】:2011-09-06 11:52:54
【问题描述】:

我使用 mockito 作为模拟框架。我这里有一个场景,我的 when(abc.method()).thenReturn(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。测试在 boolean retrunVal = response.isXXX(); 附近的类 foo 中抛出 NullPointerException;

【问题讨论】:

    标签: java junit junit4 mockito


    【解决方案1】:

    确保您的 ClassA 实现了自己的 equals 并且正确实现。

    【讨论】:

    • 我认为修改 equal 方法以使参数匹配在单元测试中起作用是不正确的...
    • @Kevin,我同意。但是,如果 ClassA 是他/她自己的类,则应该正确实现。话虽如此,我会选择你的答案而不是我的:)
    【解决方案2】:

    stub.callingmethod(request).thenReturn(response) 的参数匹配器正在比较引用相等性。你想要一个更宽松的匹配器,我认为是这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 2020-08-06
      • 2020-01-21
      相关资源
      最近更新 更多