Mockito doReturn抛出nullPointerException

时间:2017-08-16 18:21:56

标签: java mockito stubbing

我正在尝试模拟一个类的非静态方法。我正在测试同一个类的方法。但它返回一个nullPointerException。不知道我在这里做错了什么。任何帮助将不胜感激。

我的代码:

public class B2P {
    protected Future<List<FeedObject>> evaluate (NodeContext 
        nodeContext) throws Exception {
        Map<BoardQuery, Future<List<FeedObject>>> resultsFuturesMap = 
        getResultsFutureMap(boardsQuery,
        query, generatorParams, resourceContainer);

        return resultsFuturesMap;
    }

    public Map<BoardQuery, Future<List<FeedObject>>> 
      getResultsFutureMap(){
        DoSomething;
    }
}

我的测试班:

public class testClass {
  public void test() {
    B2P b2p = new B2P();
    B2P mockSpy = Mockito.spy(b2p);

    doReturn(ImmutableMap.of(
    new BoardQuery().setBoardId(102L).setSignatureWeights(
        ImmutableMap.of("s3", 1.0, "s4", 1.0, "s5", 1.0)),
    Future.value(ImmutableList.of(
        new FeedObject().setObjectId(904L).setObjectDetails(new 
            ObjectDetails()
            .setCommonObjectDetails(new CommonObjectDetails())
            .setPinDetails(new 
             PinDetails().setSource(FeedSourceType.FANTASIO))),
        new FeedObject().setObjectId(903L).setObjectDetails(new 
            ObjectDetails()
            .setCommonObjectDetails(new CommonObjectDetails())
            .setPinDetails(new PinDetails().setSource(FeedSourceType.FANTASIO))),
        new FeedObject().setObjectId(902L).setObjectDetails(new ObjectDetails()
            .setCommonObjectDetails(new CommonObjectDetails())
            .setPinDetails(new PinDetails().setSource(FeedSourceType.FANTASIO)))))))
    .when(mockSpy).getResultsFutureMap(any(), any(), any(), any());

  ....
  b2p.evaluate();

} }

我是以错误的方式嘲笑这种方法吗?

1 个答案:

答案 0 :(得分:0)

在您的普通实例上调用

attrs_name_to_search = %w( zip city last_name first_name ) fitlered_params = params.slice(*attrs_name_to_search).select { |_,v| v.present? } sql_cond = filtered_params.map { |k,_| "#{k} LIKE :#{k}" }.join(' OR ') YourModel.where(sql_cond, filtered_params) ,而不是您的模拟实例。

要调用您的模拟实例,您需要b2p.evaluate();